<template>
  <div>
    <Card title="关联合同信息" :bordered="false" >
      <a-button type="primary" style="margin-bottom: 10px"  v-if="!disabled" @click="onAppro">关联合同</a-button>
      <a-table :columns="columns" :data-source="dataList" :pagination="false" :scroll="{x: 1000}">
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.dataIndex === 'file'">
            <div v-for="item in (record.lngFileUploadList )">
              <a @click="handleDownload(item)">{{item.fileOrg}}</a>
            </div>
          </template>
          <template v-if="column.dataIndex === 'operation'">
            <a style="margin-right: 10px" @click="btnCheck('view', record, index)">查看</a>
            <a v-if="!disabled" style="margin-right: 10px" @click="btnCheck('delete', record, index)">删除</a>
          </template>
        </template>
      </a-table>
    </Card>
    <contractFactListModal @register="register" @success="handleSuccess" />
  </div>
</template>
<script lang="ts" setup>
  import { Card } from 'ant-design-vue';
  import { ref, watch} from 'vue';
  import { useRouter } from 'vue-router';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { parseDownloadUrl} from '/@/api/system/file';
  import { downloadByUrl } from '/@/utils/file/download';
  import { Modal } from 'ant-design-vue';
  import contractFactListModal from '/@/components/common/contractFactListModal.vue';
  import { useModal } from '/@/components/Modal';
  import { message } from 'ant-design-vue';

  const router = useRouter();
  const { t } = useI18n();
  const dataList = ref([])
  const columns= ref([
    { title: t('序号'), dataIndex: 'index', key: 'index', sorter: true, customRender: (column) => `${column.index + 1}` ,width: 80},
    { title: t('合同号'), dataIndex: 'kNo', sorter: true, width:180},
    { title: t('合同名称'), dataIndex: 'kName', sorter: true, width: 300},
    { title: t('关联类别'), dataIndex: 'relTypeName', sorter: true, width: 100},
    { title: t('合同类别'), dataIndex: 'kTypeName1', sorter: true, width: 100},
    { title: t('合同主体'), dataIndex: 'comName', sorter: true, width: 250},
    { title: t('我方联系人'), dataIndex: 'empName', sorter: true, width: 140},
    { title: t('联系电话'), dataIndex: 'tel', sorter: true, width: 140},
    { title: t('业务部门'), dataIndex: 'bDeptName', sorter: true, width: 140},
    { title: t('附件'), dataIndex: 'file', sorter: true, width: 140},
    { title: t('操作'), dataIndex: 'operation', width: 120, fixed: 'right',align: 'center'},
  ]);
  const [register, { openModal:openModal}] = useModal();
  const props = defineProps({
    disabled: Boolean,
    list: Array,
  });
  const emit = defineEmits(['change']);
  const handleDownload = (info) => {
    const url = parseDownloadUrl(info.response ? info.response.data.fileUrl : info.fileUrl);
    const fileName = info.response ? info.response.data.fileOrg : info.fileOrg;
    downloadByUrl({ url, fileName: fileName});
  };
  const onAppro = (val)=> {
    openModal(true,{isUpdate: false})
  }
  const handleSuccess = (val) =>{
      val.forEach(v => {
        v.id = null
      })
      if (!dataList.value.length) {
        dataList.value = val
        emit('change', dataList.value);
        return
      }
      let arr = []
      val.forEach(v => {
        dataList.value.forEach(i => {
          if (v.kNo == i.kNo){
            message.warning(v.kNo + '已重复, 合同不需要重复选择')
          } else {
            arr.push(v)
          }
        })
      })
      dataList.value = unique([...dataList.value, ...arr], 'kNo')
      emit('change', dataList.value);
    }
     function unique(arr, u_key) {
      const map = new Map()
      arr.forEach((item, index) => {
        if (!map.has(item[u_key])) {
          map.set(item[u_key], item)
        }
      })
      return [...map.values()]
    }
  const btnCheck = (btn, record, index) => {
    if (btn == 'delete') {
        Modal.confirm({
        title: '提示信息',
        content: '是否取消关联？',
        okText: '确认',
        cancelText: '取消',
        onOk() {
          dataList.value.splice(index, 1);
          emit('change', dataList.value);
        },
        onCancel() {}
    });
      
    }
    if (btn == 'view') {
      router.push({
        path: '/contract/ContractFact/form',
          query: {
          id: record.id || record.approId,
          disabled: true
        }
      })
    }
    
  }
  watch(
      () => props.disabled,
      (val) => {
        if (val) {
          let idx2 = columns.value.findIndex(v =>v.dataIndex == 'operation')
          idx2>-1 && columns.value.splice(idx2, 1)
        }
      },
      {
        immediate: true,
        deep: true,
      }
    );
  watch(
    () => props.list,
    async (val) => {
      dataList.value = val || []
    },
    {
      immediate: true,
      deep: true,
    }
  );
</script>
<style lang="less" scoped>
  .btn {
    color: #5e95ff;
    font-size: 20px; 
    font-weight: bold;
  }
</style>
