<template>
  <div>
    <el-card class="!border-none mb-4" shadow="never">
      <el-form class="mb-[-16px] formdata" :model="queryParams" inline>
        <el-form-item label="公司名称" prop="company_name">
          <el-input
            class="w-[280px]"
            v-model="queryParams.company_name"
            clearable
            placeholder="请输入公司名称"
          />
        </el-form-item>
        <el-form-item label="区" prop="area" v-show="company_type_show">
          <el-input
            class="w-[280px]"
            v-model="queryParams.area"
            clearable
            placeholder="请输入区"
          />
        </el-form-item>
        <el-form-item label="镇" prop="street" v-show="company_type_show">
          <el-input
            class="w-[280px]"
            v-model="queryParams.street"
            clearable
            placeholder="请输入镇"
          />
        </el-form-item>
        <el-form-item
          label="公司类型"
          prop="company_type"
          v-show="company_type_show"
        >
          <el-select
            v-model="queryParams.company_type"
            placeholder="请选择公司类型"
            clearable
            class="w-[280px]"
          >
            <el-option
              v-for="(item, index) in datas.dictTypeLists"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="片区经理" prop="area_manager">
          <el-input
            class="w-[280px]"
            v-model="queryParams.area_manager"
            clearable
            placeholder="请输入片区经理"
          />
        </el-form-item>
        <el-form-item label="是否签约" prop="is_contract">
          <el-select
            v-model="queryParams.is_contract"
            placeholder="是否签约"
            clearable
            class="w-[240px]"
          >
            <el-option label="已签约" value="1"></el-option>
            <el-option label="未签约" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="resetPage">查询</el-button>
          <el-button @click="resetParams">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="!border-none" v-loading="pager.loading" shadow="never">
      <router-link
        v-perms="['company/add:edit']"
        :to="{
          path: getRoutePath('company/add:edit'),
          query: {
            flag: true,
          },
        }"
      >
        <!-- <el-button type="primary" class="mb-4">
          <template #icon>
            <icon name="el-icon-Plus" />
          </template>
          创建
        </el-button> -->
      </router-link>
      <!-- <router-link
        :to="{
          path: getRoutePath('company/add:edit'),
          query: {
            id: userStore.userInfo.company_id,
            read: true,
          },
        }"
      >
        <el-button type="primary" class="mb-4">
          我的公司
        </el-button></router-link -->

      <div class="mt-4">
        <el-table :data="pager.lists" @selection-change="handleSelectionChange">
          <el-table-column
            label="id"
            prop="id"
            show-overflow-tooltip
            width="60"
          />
          <el-table-column
            label="公司名称"
            prop="company_name"
            width="250px"
            show-overflow-tooltip
          />
          <el-table-column
            label="公司类型"
            prop="company_type"
            show-overflow-tooltip
          />
          <el-table-column label="区县" prop="area" show-overflow-tooltip />
          <el-table-column label="乡镇" prop="street" show-overflow-tooltip />
          <el-table-column
            label="主联系人"
            prop="master_name"
            show-overflow-tooltip
          />
          <el-table-column
            label="联系方式"
            prop="master_phone"
            show-overflow-tooltip
          />
          <el-table-column
            label="片区经理"
            prop="area_manager"
            show-overflow-tooltip
          />
          <el-table-column
            label="是否签约"
            prop="is_contract"
            show-overflow-tooltip
          >
            <template #default="{ row }">
              <span v-if="row.is_contract == 1" style="color: #67c23a"
                >已签约</span
              >
              <span v-else style="color: #fe0000">未签约</span>
            </template></el-table-column
          >
          <el-table-column
            label="操作"
            align="center"
            width="510"
            fixed="right"
          >
            <template #default="{ row }">
              <div style="display: flex">
                <!-- <el-button type="primary" link>
                  <router-link
                    :to="{
                      path: getRoutePath('user.user/lists'),
                      query: {
                        company_id: row.id,
                        read: true,
                      },
                    }"
                    >查看成员</router-link
                  >
                </el-button> -->
                <el-button type="primary" link>
                  <router-link
                    :to="{
                      path: getRoutePath('company/subordinate/lists'),
                      query: {
                        company_id: row.id,
                        read: true,
                      },
                    }"
                    >下属公司</router-link
                  >
                </el-button>
                <el-button v-perms="['company/add:edit']" type="primary" link>
                  <router-link
                    :to="{
                      path: getRoutePath('company/add:edit'),
                      query: {
                        id: row.id,
                        read: true,
                        isshow: true,
                      },
                    }"
                    >详情</router-link
                  >
                </el-button>
                <!-- <el-button v-perms="['company/add:edit']" type="primary" link>
                  <router-link
                    :to="{
                      path: getRoutePath('company/add:edit'),
                      query: {
                        id: row.id,
                        edit: true,
                      },
                    }"
                    >编辑</router-link
                  >
                </el-button>
                <el-button
                  v-perms="['company/delete']"
                  type="danger"
                  link
                  @click="handleDelete(row.id)"
                  >删除</el-button
                > -->
                <el-button
                  v-if="row.is_authentication == 0"
                  v-perms="['company/authentication']"
                  type="primary"
                  link
                  @click="handleAuthentication(row.id)"
                  >企业认证</el-button
                >
                <template v-if="row.is_authentication && row.is_contract == 0">
                  <el-button
                    v-if="
                      Array.isArray(row.contract) && row.contract.length == 0
                    "
                    v-perms="['company/initiate_contract']"
                    type="primary"
                    link
                    @click="showChangeCompany(row)"
                    >生成合同</el-button
                  >
                  <el-button
                    v-else-if="row.contract?.check_status == 1"
                    v-perms="['company/initiate_contract']"
                    type="warning"
                    link
                    @click="auditing"
                    >审核中</el-button
                  >
                  <el-button
                    v-else-if="row.contract?.check_status == 2"
                    v-perms="['company/Draftingcontracts']"
                    type="primary"
                    link
                    @click="showCreateConctPop(row)"
                    >发送合同</el-button
                  >
                  <el-button
                    v-else-if="row.contract?.check_status == 3"
                    v-perms="['company/postsms']"
                    type="primary"
                    link
                    @click="(showPop = true), (contractId = row.id)"
                    >发送短信</el-button
                  >
                </template>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="flex mt-4 justify-end">
        <pagination v-model="pager" @change="getLists" />
      </div>
    </el-card>
    <el-dialog
      v-model="showInitiateContractPop"
      @close="offInitiateContractPop"
    >
      <h1>重要提醒</h1>
      <div>
        <div class="content">请确认信息是否有误</div>
        <el-card>
          <el-row>
            <el-col :span="12">
              <el-form-item label-width="100px" label="甲方" prop="field130">
                <el-input
                  v-model="contractFormData.party_a_name"
                  placeholder="请选择甲方"
                  @click="showCompany = true"
                  clearable
                  :style="{ width: '100%' }"
                ></el-input>
                <!-- <el-select
                  v-model="contractFormData.party_a"
                  placeholder="请选择甲方"
                  clearable
                  :style="{ width: '100%' }"
                >
                  <el-option
                    v-for="(item, index) in company_list"
                    :key="index"
                    :label="item.company_name"
                    :value="item.id"
                  ></el-option>
                </el-select> -->
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label-width="100px" label="乙方" prop="field131">
                <el-input
                  :disabled="true"
                  v-model="contractFormData.party_b_name"
                  placeholder="请选择乙方"
                  clearable
                  :style="{ width: '100%' }"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label-width="100px"
                label="合同类型"
                prop="contract_type"
              >
                <el-select
                  v-model="contractFormData.contract_type"
                  placeholder="请选择合同类型"
                  clearable
                  :style="{ width: '100%' }"
                >
                  <el-option
                    v-for="(item, index) in contract_type"
                    :key="index"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item
                label-width="100px"
                label="合同编号"
                prop="field133"
              >
                <el-input
                  placeholder="系统自动生成"
                  v-model="contractFormData.contract_no"
                  clearable
                  :style="{ width: '100%' }"
                  :disabled="true"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
      </div>
      <p class="btn_menu">
        <el-button type="primary" size="large" @click="InitiateContract"
          >确认</el-button
        >
        <el-button type="info" size="large" @click="offInitiateContractPop"
          >返回</el-button
        >
      </p>
      <el-dialog v-model="showCompany">
        <DialogIndex
          :companyTypeList="datas.dictTypeLists"
          :type="30"
          @customEvent="customEvent"
        ></DialogIndex>
      </el-dialog>
    </el-dialog>
    <el-dialog v-model="showPop" @close="offPop">
      <h1>重要提醒</h1>
      <div class="content" v-if="showConctactPop">
        请确认信息是否有误,发送合同,请确认信息是否有误,发送电子合同后短时间内将不可再次发送.
      </div>
      <div class="content" v-else>
        确认签约短信将在60秒后发送,请注意查收,并点击短信链接进行线上合同签约
      </div>
      <p class="btn_menu">
        <el-button
          type="primary"
          size="large"
          v-if="showConctactPop"
          @click="creContct"
          >确认</el-button
        >
        <el-button type="primary" size="large" v-else @click="sendMsg"
          >确认</el-button
        >
        <el-button type="info" size="large" @click="offPop">返回</el-button>
      </p>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup name="companyLists">
import { usePaging } from "@/hooks/usePaging";
import { useDictData } from "@/hooks/useDictOptions";
import useUserStore from "@/stores/modules/user";
import {
  apiCompanyLists,
  companyListTwo,
  apiCompanyDelete,
  generateGontract,
  sendMsgApi,
  authentication,
  apiCompanyDetail,
  initiate_contract,
} from "@/api/company";
import { timeFormat } from "@/utils/util";
import feedback from "@/utils/feedback";
import { dictDataLists } from "@/api/setting/dict";
import { getRoutePath } from "@/router";
import { dictContractTypeList } from "@/utils/dict.ts";
import DialogIndex from "./dialog_index.vue";

const showCompany = ref(false);
const customEvent = (e: any) => {
  contractFormData.value.party_a = e.id;
  contractFormData.value.party_a_name = e.company_name;
  showCompany.value = false;
};

const userStore = useUserStore();
console.log(userStore.userInfo.company_id);
const route = useRoute();
const company_type_show = ref(true);
// 创建合同与发送短信
//弹窗
const showPop = ref(false);
const showConctactPop = ref(false);
const offPop = () => {
  showPop.value = false;
  showConctactPop.value = false;
};
const InitiateContractPop = ref(false);
const showInitiateContractPop = ref(false);
const offInitiateContractPop = () => {
  showInitiateContractPop.value = false;
  InitiateContractPop.value = false;
};
// 创建合同的id
const contractId = ref("");

// 合同
const contractFormData = ref({
  party_a: "",
  party_a_name: "",
  party_b: "",
  party_b_name: "",
  contract_type: "",
  contract_no: "",
});

const company_list = ref([]);
const contract_type = ref([]);

const getDetails = async (id: any) => {
  const data = await apiCompanyDetail({
    id: id,
  });
  companyListTwo().then((res) => {
    company_list.value = res;
  });
  dictDataLists({ type_id: 7 }).then((res) => {
    contract_type.value = res.lists.filter((item: any) => {
      return dictContractTypeList.find((t: String | Number) => t == item.id);
    });
  });
  contractFormData.value.party_b = data.id;
  contractFormData.value.party_b_name = data.company_name;
  if (userStore.userInfo.company.id) {
    contractFormData.value.party_a = userStore.userInfo.company.id;
    contractFormData.value.party_a_name =
      userStore.userInfo.company.company_name;
  } else {
    contractFormData.value.party_a = "";
    contractFormData.value.party_a_name = "";
  }
};

const showChangeCompany = (row: any) => {
  contractId.value = row.id;
  getDetails(row.id);
  // showPop.value = true
  ShowInitiateContractPop();
};

const ShowInitiateContractPop = () => {
  (InitiateContractPop.value = true), (showInitiateContractPop.value = true);
};
const showCreateConctPop = (row) => {
  (showPop.value = true),
    (showConctactPop.value = true),
    (contractId.value = row.id);
};
const InitiateContract = async () => {
  await initiate_contract({
    id: contractId.value,
    ...contractFormData.value,
  });
  getLists();
  offInitiateContractPop();
};
const creContct = async () => {
  await generateGontract({ id: contractId.value });
  getLists();
  offPop();
};
const sendMsg = async () => {
  await sendMsgApi({ id: contractId.value });
  getLists();
  offPop();
};
// 创建合同与发送短信结束
// 查询条件
const queryParams = reactive({
  company_name: "",
  area: "",
  street: "",
  company_type: "",
  area_manager: "",
  // 是否签约
  is_contract: "",
});

if (route.query.company_type) {
  company_type_show.value = false;
  queryParams["company_type"] = route.query.company_type?.toString() || "";
}

const datas = reactive({
  dictTypeLists: [],
});
const getdictTypeLists = async () => {
  const data = await dictDataLists({ type_id: 6 });
  datas["dictTypeLists"] = data["lists"];
};
getdictTypeLists();
// 选中数据
const selectData = ref<any[]>([]);

// 表格选择后回调事件
const handleSelectionChange = (val: any[]) => {
  selectData.value = val.map(({ id }) => id);
};

// 获取字典数据
const { dictData } = useDictData("");

// 分页相关
const { pager, getLists, resetParams, resetPage } = usePaging({
  fetchFun: apiCompanyLists,
  params: queryParams,
});

// 删除
const handleDelete = async (id: number | any[]) => {
  await feedback.confirm("确定要删除？");
  await apiCompanyDelete({ id });
  getLists();
};
const handleAuthentication = async (id: number | any[]) => {
  await feedback.confirm("确定要认证？");
  await authentication({ id });
  getLists();
};

// 审核中
const auditing = () => {
  ElMessage.warning("请等待合同审核完成!");
};

getLists();
</script>
<style lang="scss">
.btn {
  position: absolute;
}
h1 {
  text-align: center;
  font-weight: bold;
  font-size: 30px;
  color: red;
  margin-bottom: 10px;
}

.content {
  font-size: 20px;
}

.info {
  color: red;
  font-weight: bold;
  font-size: 18px;
  display: inline-block;
  margin: 0 5px;
}

.btn_menu {
  margin-top: 10vh;
  display: flex;
  justify-content: space-around;
}
.formdata {
  .el-form-item {
    width: 20%;
  }
}
</style>
