<template>
  <div class="card-search">
    <a-form ref="formRef" name="advanced_search" class="ant-advanced-search-form" :model="searchParams">
      <a-row :gutter="24">
        <a-col :span="6">
          <a-form-item label="企业名称" :label-col="{span:6}" name="companyName">
            <a-input v-model:value="searchParams.companyName" placeholder="" :allow-clear="true"/>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="统一信用代码" :label-col="{span:6}" name="companyCode">
            <a-input v-model:value="searchParams.companyCode" placeholder="" :allow-clear="true"/>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="企业状态" :label-col="{span:6}" name="recordStatus">
            <a-select
              ref="select"
              v-model:value="searchParams.recordStatus"
              :options="recordStatusList"
              :field-names="{ label: 'name', value: 'value' }"
              :allow-clear="true"
              @change="loadData"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="6" style="text-align: left">
          <a-button type="primary" html-type="submit" @click="onSearch" >查询</a-button>
          <a-button
            style="margin: 0 8px"
            @click="
              () => {
                formRef.resetFields();
                loadData();
              }
            ">重置</a-button>
          <a style="font-size: 12px" @click="expand = !expand">
            <template v-if="expand">
              <UpOutlined />
            </template>
            <template v-else>
              <DownOutlined />
            </template>
            {{ expand ? '收缩' : '展开' }}
          </a>
        </a-col>
      </a-row>
      <a-row :gutter="24" v-show="expand">
        <a-col :span="6">
          <a-form-item label="所属县区" :label-col="{span:6}" name="regionCode">
            <a-select
              ref="select"
              v-model:value="searchParams.regionCode"
              :options="regionList"
              :field-names="{ label: 'name', value: 'code' }"
              :allow-clear="true"
              @change="changeCity"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="所属街道" :label-col="{span:6}" name="streetCode">
            <a-select
              ref="select"
              v-model:value="searchParams.streetCode"
              :options="streetList"
              :field-names="{ label: 'name', value: 'code' }"
              :allow-clear="true"
              @change="loadData"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="6">
        </a-col>
        <a-col :span="6">
        </a-col>
      </a-row>
      <a-row class="edit-operation">
        <a-col :span="24" style="text-align: right">
          <a-button type="primary" html-type="submit" @click='onAdd' functioncode="T01020102">新增</a-button>
          <BImportExcel functioncode="T01020105"
            :options="importOptions"
            @success="loadData"
          ></BImportExcel>
          <BExportExcel :title="'导出'" :filename="'企业信息'"
                        :url="'companyService/company/export'"
                        :params="{...exportSearchParams, isExport: true, rows:10000,companyIDList:formState.selectedRowKeys.join(',')}"></BExportExcel>
        </a-col>
      </a-row>
    </a-form>
    <div class="search-result-list">
      <a-table :columns="columns" :data-source="dataList" :scroll="{ x:'100%', y: 500 }" :pagination="pagination"
               :loading="formState.loading"
               @change="handleTableChange"
               :row-selection="{ selectedRowKeys: formState.selectedRowKeys, onChange: onSelectChange}"
               :row-key="record=>record.companyID"
               bordered>
        <template #bodyCell="{ column, text, record }">
          <template v-if="column.key === 'operation'">
            <div class="table-operation">
              <a-button type="link" size="small" @click='onDetail(record)' functioncode="T01020101">查看</a-button>
              <a-button type="link" size="small" @click='onEdit(record)' functioncode="T01020103">编辑</a-button>
              <a-button type="link" size="small" @click="onDel(record)" functioncode="T01020104">删除</a-button>
            </div>
          </template>
          <template v-if="column.key === 'postCount'">
            <div style="text-align: center;">
              <a-button v-if="record.postCount>0"  name="postCount" type="link" size="small" @click='onShowPosition(record)' >{{ record.postCount }}</a-button>
              <a-button v-if="record.postCount==0"  type="link" size="small" >0</a-button>
            </div>
          </template>
        </template>
      </a-table>
    </div>
    <PositionShowModal ref="modalShowRef"  ></PositionShowModal>
  </div>
</template>

<script lang="ts">
import {computed, createVNode, defineComponent, reactive, ref} from 'vue';
import {DownOutlined, ExclamationCircleOutlined, UpOutlined} from '@ant-design/icons-vue';
import type {FormInstance, TableColumnsType, TableProps} from 'ant-design-vue';
import {Modal, SelectProps} from "ant-design-vue";
import {del, getList} from '@/api/companyService/company';
import BExportExcel from "@/components/basic/excel/exportExcel/exportExcel.vue";
import BImportExcel from '@/components/basic/excel/importExcel/importExcel.vue';
import {getPaginationTotalTitle} from "@/utils/common";
import dayjs from "dayjs";
import {useTabsViewStore} from '@/store/modules/tabsView';
import {get} from "@/api/common";
import type {ImportProps} from '@/components/basic/excel/importExcel/ImportProps';
import PositionShowModal from './show.vue';

export default defineComponent({
  components: {DownOutlined, UpOutlined, BExportExcel, BImportExcel, PositionShowModal},
  setup() {
    const formRef = ref<FormInstance>();
    const modalShowRef = ref();
    const searchParams = reactive({
      pageIndex: 1,
      pageSize: 20,
      companyName: '',
      companyCode: '',
      recordStatus: '',
      regionCode: '',
      streetCode: ''
    });
    // 导出Excel查询参数
    const exportSearchParams = computed(() => {
      let data = JSON.parse(JSON.stringify(searchParams));
      data.pageSize = formState.total;
      return data;
    })
    const formState = reactive({
      total: 0,
      selectedRowKeys: [],
      loading: false
    });
    const expand = ref(false);
    const importOptions = ref<ImportProps>({
      title: '导入',
      url: 'companyService/company/importCompany',
      columns: [
        {cnName: '统一信用代码', enName: 'companyCode', width: 140},
        {cnName: '企业名称', enName: 'companyName', width: 100},
        {cnName: '所属驿站', enName: 'SiteName', width: 100},
        {cnName: '企业办公地址', enName: 'companyAddress', width: 100},
        {cnName: '企业联系人', enName: 'userName', width: 100},
        {cnName: '企业联系电话', enName: 'userMobile', width: 100},
        {cnName: '企业状态', enName: 'recordStatusName', width: 100},
        {cnName: '是否缺工', enName: 'isShortageName', width: 100},
        {cnName: '法定代表人(负责人)', enName: 'frName', width: 140},
        {cnName: '营业执照有效期', enName: 'validTime', width: 100},
        {cnName: '企业邮箱', enName: 'companyEmail', width: 100},
        {cnName: '企业分类', enName: 'companyTypeStr', width: 100},
        {cnName: '所属县区', enName: 'regionName', width: 100},
        {cnName: '所属街道', enName: 'streetName', width: 100},
        {cnName: '企业规模', enName: 'companyModelStr', width: 100},
        {cnName: '用工情况(人)', enName: 'workSituation', width: 100},
        {cnName: '参保人数(人)', enName: 'insuredCount', width: 100},
        {cnName: '经营范围', enName: 'businScope', width: 100},
        {cnName: '企业简介', enName: 'companyDesc', width: 100}
      ],
      template: {
        tempFileName: '企业信息导入模板.xlsx',
        url: '',
        params: null,
      },
    });
    const columns: TableColumnsType = [
      {
        title: '序号',
        align: "center",
        key: 'companyID',
        width:60,
        customRender: item => `${searchParams.pageSize * (searchParams.pageIndex - 1) + item.index + 1}`
      },
      {title: '企业名称', dataIndex: 'companyName', key: 'companyName',width: 200, align: "center"},
      {title: '所属县区', dataIndex: 'regionName', key: 'regionName', width: 120, align: "center"},
      {title: '所属街道', dataIndex: 'streetName', key: 'streetName', width: 120,align: "center"},
      {title: '所属驿站', dataIndex: 'siteName', key: 'siteName', width: 200, align: "center"},
      {title: '统一信用代码', dataIndex: 'companyCode', key: 'companyCode', width: 200,align: "center"},
      {
        title: '企业状态', dataIndex: 'recordStatus', key: 'recordStatus',width: 120, align: "center", customRender: (item) => {
          return item.record.recordStatus == 1 ? "在营" : "关闭";
        }
      },
      {title: '参保人数', dataIndex: 'insuredCount', key: 'insuredCount', width: 100,align: "center"},
      {title: '企业规模', dataIndex: 'companyModelType', key: 'companyModelType',width: 120, align: "center"},
      {title: '当前岗位数量', dataIndex: 'postCount', key: 'postCount', width: 120,align: "center"},
      {title: '录入人', dataIndex: 'createUserName', key: 'createUserName', width: 120,align: "center"},
      {
        title: '录入时间   ', dataIndex: 'createTime', key: 'createTime',width: 120, align: "center", customRender: (item) => {
          return item.record.createTime == null ? "" : (dayjs(item.record.createTime).format('YYYY-MM-DD'))
        }
      },
      {title: '操作', key: 'operation', fixed: 'right', width: 150, align: "center"},
    ];
    const pagination = computed(() => ({
      total: formState.total,
      current: searchParams.pageIndex,
      pageSize: searchParams.pageSize,
      showSizeChanger: true,
      showTotal: total => getPaginationTotalTitle(total)
    }));

    const recordStatusList =ref<SelectProps['options']>([
      { value: 1, name: '在营' },
      { value: 0, name: '停业' },
    ]);
    const regionList = ref<SelectProps['options']>();
    const streetList = ref<SelectProps['options']>();
    const dataList = ref([]);
    const institutionEditModelRef = ref();
    const tabsViewStore = useTabsViewStore();

    const changeCity = () => {
      if(searchParams.regionCode){
        get('system/area/getAreaList', {code: searchParams.regionCode}).then(data => {
          // console.log(data);
          streetList.value = data;
          // console.log(streetList.value);
        })
      }
      loadData();
    }

    get('system/area/getCityList', {}).then(data => {
      regionList.value = data;
      // console.log(regionList.value);
    });

    const loadData = async function () {
      formState.loading = true;
      const result: any = await getList(searchParams);
      dataList.value = result.list;
      formState.total = result.total;
      formState.loading = false;
    }

    const handleTableChange: TableProps['onChange'] = (pag: { pageSize: number; current: number },) => {
      searchParams.pageIndex = pag.current;
      searchParams.pageSize = pag.pageSize;
      loadData();
    };

    const onSelectChange = (selectedRowKeys: any) => {
      formState.selectedRowKeys = selectedRowKeys;
    };

    const onSearch = () => {
      loadData();
    }

    const onShowPosition = async function(record){
      const curPositionList :any = await get("companyService/post/getPostsByCompanyID",{companyId:record.companyID});
      console.log(curPositionList);
      modalShowRef.value.show(curPositionList);
    }

    const onDel = (item: any) => {
      Modal.confirm({
        title: '确认删除选中的企业信息?',
        icon: createVNode(ExclamationCircleOutlined),
        content: '',
        okText: '确认删除',
        okType: 'danger',
        okButtonProps: {},
        cancelText: '取消',
        onOk() {
          del([item.companyID]).then(() => {
            loadData();
          });
        },
        onCancel() {

        },
      });
    };

    const onAdd = () => {
      tabsViewStore.addTabByPath('/companyService/enterprise/add', {id: null, op: 1});
    };

    const onEdit = (item: any) => {
      tabsViewStore.addTabByPath('/companyService/enterprise/edit', {id: item.companyID, op: 2});
    };

    const onDetail = (item: any) => {
      tabsViewStore.addTabByPath('/companyService/enterprise/detail', {id: item.companyID});
    };

    return {
      formRef,
      modalShowRef,
      searchParams,
      formState,
      columns,
      pagination,
      dataList,
      expand,
      institutionEditModelRef,
      handleTableChange,
      loadData,
      onSelectChange,
      changeCity,
      onSearch,
      onDel,
      onAdd,
      onEdit,
      onShowPosition,
      importOptions,
      recordStatusList,
      regionList,
      streetList,
      onDetail,
      exportSearchParams
    };
  },
  created() {
    this.loadData();
  },
  activated() {
    if (history.state.params?.reload)
      this.loadData();
  }
});
</script>
