<template>
  <PageWrapper dense fixedHeight contentFullHeight>
    <RiskAssessment
      :isView="showPageType === 1"
      :id="recordId"
      @return-page="returnPage"
      v-if="[0, 1].includes(showPageType)"
    />
    <Application
      :id="recordId"
      :isAssess="isAssess"
      @return-page="returnPage"
      v-else-if="showPageType === 2"
    />
    <BasicTable @register="registerTable" v-else>
      <template #toolbar>
        <a-button type="primary" v-auth="'potential:add'" @click="handleCreate">
          {{ t('新增') }}
        </a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex == 'state'">
          <span>{{ getState(record.state) }}</span>
        </template>
        <template v-if="column.dataIndex == 'type' && !!record.type">
          <a-tag
            v-for="(item, index) in record.type.split(',')"
            :key="index"
            :color="getType(item, false)"
          >
            {{ getType(item, true) }}
          </a-tag>
        </template>
        <template v-if="column.dataIndex == 'action'">
          <TableAction
            :actions="[
              {
                label: '编辑',
                onClick: handleEdit.bind(null, record),
              },
              {
                label: record.assessState === 0 ? '风险评估' : '评估查看',
                onClick: showPage.bind(null, record),
              },
              {
                label: '转正申请',
                onClick: showPageTwo.bind(null, record),
              },
              {
                label: '删除',
                color: 'error',
                onClick: handleDelete.bind(null, record),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <PotentialModal @register="registerModal" @success="reload" />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { createVNode, ref, onMounted } from 'vue';
  import { BasicTable, useTable, BasicColumn, FormSchema, TableAction } from '/@/components/Table';

  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { PageWrapper } from '/@/components/Page';
  import { getSupplierPageList, deleteSupplier } from '/@/api/erp/supplier/list';
  import { getDicDetailList } from '/@/api/system/dic';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import PotentialModal from './components/PotentialModal.vue';
  import RiskAssessment from './components/RiskAssessment.vue';
  import Application from './components/Application.vue';
  import { usePermission } from '/@/hooks/web/usePermission';

  const { t } = useI18n();
  const columns: BasicColumn[] = [
    {
      title: '供应商编码',
      dataIndex: 'number',
      resizable: true,
    },
    {
      title: '供应商名称',
      dataIndex: 'name',
      resizable: true,
    },
    {
      title: '供应商负责人',
      dataIndex: 'person',
      width: 100,
      resizable: true,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      width: 100,
      resizable: true,
    },
    {
      title: '是否评估',
      dataIndex: 'assessStateName',
      width: 100,
      resizable: true,
    },
    {
      title: '经营范围',
      dataIndex: 'scope',
      resizable: true,
    },
    {
      title: '添加时间',
      dataIndex: 'createDate',
      resizable: true,
    },
    {
      title: '状态',
      dataIndex: 'state',
      resizable: true,
      width: 60,
    },
    {
      title: '供应商类型',
      dataIndex: 'type',
      width: 220,
      resizable: true,
    },
  ];

  const searchFormSchema: FormSchema[] = [
    {
      field: 'name',
      label: '供应商名称',
      component: 'Input',
      colProps: { span: 8 },
      componentProps: {
        placeholder: '请输入供应商名称',
      },
    },
    {
      field: 'finalState',
      label: '风险评估',
      component: 'XjrSelect',
      colProps: { span: 8 },
      componentProps: {
        datasourceType: 'dic',
        params: { itemId: '1676831752869834753' },
        labelField: 'name',
        valueField: 'id',
        placeholder: '请选择风险评估',
        getPopupContainer: () => document.body,
      },
    },
    {
      field: 'createDate',
      label: '添加时间',
      component: 'RangePicker',
      colProps: { span: 8 },
      componentProps: {
        format: 'YYYY-MM-DD',
        getPopupContainer: () => document.body,
      },
    },
    {
      field: 'type',
      label: '供应商类别',
      component: 'XjrSelect',
      colProps: { span: 8 },
      componentProps: {
        datasourceType: 'dic',
        params: { itemId: '1676483934342787074' },
        labelField: 'name',
        valueField: 'id',
        placeholder: '请选择供应商类别',
        getPopupContainer: () => document.body,
      },
    },
  ];

  const { notification } = useMessage();
  const { hasPermission } = usePermission();

  const [registerModal, { openModal }] = useModal();

  const recordId = ref('');
  const showPageType = ref<any>('');
  const isAssess = ref(false); //是否风险评估

  const typeOptions = ref<Recordable[]>([]);
  const [registerTable, { reload }] = useTable({
    title: '潜在供应商',
    api: getSupplierPageList,
    rowKey: 'id',
    columns,
    formConfig: {
      rowProps: {
        gutter: 16,
      },
      schemas: searchFormSchema,
      fieldMapToTime: [['createDate', ['startTime', 'endTime'], 'YYYY-MM-DD', true]],
      showResetButton: false,
    },
    beforeFetch: (params) => {
      return { ...params, state: 0 };
    },
    useSearchForm: true,
    showTableSetting: true,
    striped: false,
    actionColumn: {
      width: 230,
      title: t('操作'),
      dataIndex: 'action',
    },
    customRow: (record) => {
      return {
        ondblclick: () => {
          if (hasPermission('potential:edit')) {
            handleEdit(record);
          }
        },
      };
    },
    tableSetting: {
      size: false,
    },
  });

  onMounted(async () => {
    typeOptions.value = await getDicDetailList({ itemId: '1676483934342787074' });
  });

  const getState = (state) => {
    switch (state) {
      case 0:
        return '潜在';
      case 1:
        return '正式';
      case 2:
        return '淘汰';
    }
  };

  const getType = (type, isText) => {
    const data = typeOptions.value.filter((x) => x.id === type);
    if (!data.length) return '';
    if (isText) return data[0].name;
    switch (data[0].name) {
      case '原料':
        return 'processing';
      case '成品':
        return 'error';
      case '半成品':
        return 'success';
      case '其它':
        return 'warning';
    }
  };

  const handleCreate = () => {
    openModal(true, {
      isUpdate: false,
      title: '潜在',
    });
  };

  const handleEdit = (record) => {
    openModal(true, {
      id: record.id,
      isUpdate: true,
      title: '潜在',
    });
  };

  const handleDelete = (record) => {
    Modal.confirm({
      title: t('提示信息'),
      icon: createVNode(ExclamationCircleOutlined),
      content: t('是否确认删除？'),
      okText: t('确认'),
      cancelText: t('取消'),
      async onOk() {
        await deleteSupplier(record.id);
        notification.success({
          message: t('提示'),
          description: t('删除成功'),
        });
        reload();
      },
      onCancel() {},
    });
  };

  const showPage = (record) => {
    showPageType.value = record.assessState;
    recordId.value = record.id;
  };
  const showPageTwo = (record) => {
    showPageType.value = 2;
    recordId.value = record.id;
    isAssess.value = !!record.assessState;
  };
  const returnPage = () => {
    showPageType.value = '';
    reload();
  };
</script>
<style lang="less" scoped>
  .actionTxt {
    padding: 4px 2px;

    &:last-child {
      color: #f56c6c;
    }
  }

  :deep(.ant-tag) {
    margin-right: 5px;
  }
</style>
