<template>
  <div class="table-box">
    <ProTable :config="config" ref="ProTableRef" :api="getTrackRecord"
        :paramCallback="paramCallback">
    </ProTable>
    <callDrawer ref="callDrawerRef" @success="query()" :mode="callMode"></callDrawer>
    <el-image-viewer :url-list="srcList" v-if="RefImage" @close="RefImage = false" />

  </div>
</template>

<script setup name="systemLog" lang="jsx">
  import { computed } from 'vue';
  import { reactive, ref } from 'vue';
  import { getTrackRecord } from '@/api/property';
  import { onMounted } from 'vue';
  import { getAppEnvConfig } from '@/utils/env';
  import { ElMessageBox, ElMessage, ElButton, ElTag } from 'element-plus';
  import callDrawer from './components/callDrawer.vue';
  import { Download } from '@element-plus/icons-vue';
  import { inject } from 'vue';
  const envs = getAppEnvConfig();
  const downloadfile = inject('download');
  const ProTableRef = ref();
  const callMode = ref('');
  const showModal = ref(false);
  const selectdList = ref([]);
  const onCheckboxChange = (row) => {
    console.log('row', row);
    selectdList.value = row.records;
  };
  const callDrawerRef = ref();
  const srcList = ref([]);
  const RefImage = ref(false);
  const options = [
    {
      value: 2,
      label: '2',
    },
    {
      value: 3,
      label: '3',
    },
    {
      value: 4,
      label: '4',
    },
    {
      value: 5,
      label: '5',
    },
    {
      value: 6,
      label: '6',
    },
  ];
  const preview = (item, type) => {
    const list = [];
    item[type].forEach((v) => {
      list.push(envs.VITE_GLOB_API_URL_PREFIX + '/sys/static/' + v);
    });
    RefImage.value = true;
    srcList.value = list;
  };
  const download = (item) => {
    const name = item.slice(item.lastIndexOf('/') + 1, item.length);
    downloadfile(envs.VITE_GLOB_API_URL_PREFIX + '/sys/static/' + item, {}, name);
  };
  const auditStatusOpt = [
    { label: '未稽核', value: 'un_audit' },
    { label: '稽核中', value: 'audit' },
    { label: '已拒绝', value: 'rejected' },
    { label: '已完成', value: 'complete' },
    { label: '稽核通过', value: 'passed' },
  ];
  const changeStatus = async () => {
    showModal.value = true;
  };
  const submitForm = async (type) => {
    const ids = selectdList.value.map((v) => v.id).join(',');
    await byStagesflowStatusByIds({
      ids: ids,
      flowStatus: type,
    });

    ElMessage.success({
      message: '审核成功',
      plain: true,
    });
    showModal.value = false;

    query();
  };
  const callTelephone = (row, type) => {
    callMode.value = type;
    callDrawerRef.value.openModal(JSON.parse(JSON.stringify(row)));
  };
  const followStatusOpt = [
    { label: '接通后挂断', value: 'hang_up' },
    { label: '接通有实质进展', value: 'progress' },
    { label: '接通有效转告', value: 'pass_on' },
    { label: '接通拒绝转告', value: 'no_pass' },
    { label: '接听后挂断', value: 'Hang_up_after_answering' },
    { label: '接通无应答', value: 'No_response_when_connected' },
    { label: '称与债人无关', value: 'Claims_unrelated_to_creditors' },
    { label: '称非本人', value: 'Claiming_not_to_be_myself' },
    { label: '无人接听', value: 'no_answer' },
    { label: '关机', value: 'Shutdown' },
    { label: '空号', value: 'dead_number' },
    { label: '占线/忙音/正在通话中', value: 'Busy' },
    { label: '停机', value: 'closing_down' },
    { label: '机器人回复', value: 'Robot_reply' },
    { label: '微信', value: 'WeChat' },
    { label: '短信', value: 'short_message' },
    { label: 'QQ', value: 'QQ' },
    { label: '飞书', value: 'fly' },
    { label: '钉钉', value: 'DING' },
  ];
  const phoneResultStatusOpt = [
    { label: '后续再跟进', value: 'later' },
    { label: '承诺还款', value: 'Promise_Repayment' },
    { label: '暂无还款意愿', value: 'No_Repay' },
    { label: '要求停催', value: 'Stop_Urging' },
    { label: '情绪激动抗拒', value: 'resistance' },
    { label: '拒绝还款', value: 'Refuse_Repayment' },
    { label: '已还款', value: 'Repaired' },
    { label: '代履行还款', value: 'repayment_others' },
  ];
  const caseStatusOpt = [
    { label: '正常', value: 'normal' },
    { label: '撤案', value: 'withdraw' },
    { label: '留案', value: 'stay' },
  ];
  const paramCallback = (param) => {
    const obj = JSON.parse(JSON.stringify(param));
    obj['auditStatus'] = 'complete';
    if (obj['trackTime']) {
      if (obj['trackTime'][0]) obj['trackTimeBegin'] = obj['trackTime'][0];
      if (obj['trackTime'][1]) obj['trackTimeEnd'] = obj['trackTime'][1];
      delete obj['trackTime'];
    }
    if (obj['nextTime']) {
      if (obj['nextTime'][0]) obj['nextTrackTimeBegin'] = obj['nextTime'][0];
      if (obj['nextTime'][1]) obj['nextTrackTimeEnd'] = obj['nextTime'][1];
      delete obj['nextTime'];
    }
    // obj['voices'] = 'Y'
    // obj['images'] = 'Y'
    // obj['notes'] = 'Y'
    // obj['others'] = 'Y'
    return obj;
  };
  const config = computed(() => {
    return {
      rowStyle ({ row }) {
        if (row.auditDesc === 'time_out') {
          return {
            backgroundColor: 'rgb(242,217,217)'
          }
        }
      },
      columns: [
        { field: 'id', title: '跟进记录ID', showOverflow: 'tooltip', width: 90 },
        {
          field: 'caseId',
          title: '案件ID',
          showOverflow: 'tooltip',
          width: 80,
          search: { el: 'input', props: { clearable: true }, labelWidth: 78 },
          slots: {
            default: ({ row }) => {
              return <>{row.loans.map((v) => v.caseId).join(',')}</>;
            },
          },
        },
        {
          field: 'trackTime',
          title: '跟进日期',
          showOverflow: 'tooltip',
          width: 100,
          search: {
            el: 'date-picker',
            props: { type: 'daterange', valueFormat: 'YYYY-MM-DD' },
            labelWidth: 78,
          },
        },
        {
          field: 'nextTime',
          title: '下次跟进时间',
          showOverflow: 'tooltip',
          width: 110,
          search: {
            el: 'date-picker',
            props: { type: 'daterange', valueFormat: 'YYYY-MM-DD' },
            labelWidth: 78,
          },
        },
        {
          field: 'guarantor.name',
          title: '联系人姓名',
          showOverflow: 'tooltip',
          width: 110,
          search: { el: 'input', props: { clearable: true }, key: 'guarantorName', labelWidth: 78 },
        },
        {
          field: 'guarantor.phone',
          title: '联系人号码',
          showOverflow: 'tooltip',
          width: 110,
          search: {
            el: 'input',
            props: { clearable: true },
            key: 'guarantorPhone',
            labelWidth: 78,
          },
          labelWidth: 78,
        },
        {
          field: 'followStatus',
          title: '拨打跟进结果',
          showOverflow: 'tooltip',
          width: 120,
          enum: followStatusOpt,
          search: {
            el: 'select',
            props: { filterable: true, multiple: true, 'collapse-tags': true },
            labelWidth: 78,
            defaultValue: [
              'progress',
              'pass_on',
              'no_pass',
              'Claims_unrelated_to_creditors',
              'Claiming_not_to_be_myself',
            ],
          },
          fieldNames: { label: 'label', value: 'value' },
          slots: {
            default: ({ row }) => {
              return (
                <>
                  {row.followStatus
                    ? followStatusOpt.find((v) => v.value === row.followStatus).label
                    : ''}
                </>
              );
            },
          },
        },
        {
          field: 'phoneResultStatus',
          title: '拨打处置状态',
          showOverflow: 'tooltip',
          width: 120,
          enum: phoneResultStatusOpt,
          search: { el: 'select', props: { filterable: true }, labelWidth: 78 },
          fieldNames: { label: 'label', value: 'value' },
          slots: {
            default: ({ row }) => {
              return (
                <>
                  {row.phoneResultStatus
                    ? phoneResultStatusOpt.find((v) => v.value === row.phoneResultStatus).label
                    : ''}
                </>
              );
            },
          },
        },
        {
          field: 'trackRecord.auditStatus',
          title: '稽核状态',
          showOverflow: 'tooltip',
          width: 80,
          slots: {
            default: ({ row }) => {
              return (
                <>
                  {row.auditStatus
                    ? auditStatusOpt.find((v) => v.value === row.auditStatus).label
                    : ''}
                </>
              );
            },
          },
        },
        {
          field: 'remark',
          title: '备注',
          showOverflow: 'tooltip',
          width: 80,
          search: { el: 'input', props: { clearable: true }, labelWidth: 78 },
        },
        {
          field: 'voices',
          title: '通话录音',
          showOverflow: 'tooltip',
          width: 80,
          slots: {
            default: ({ row, rowIndex }) => {
              if (row.voices && row.voices.length > 0) {
                return (
                  <>
                    {row.voices.map((item, index) => (
                      <el-icon>
                        <Download onClick={() => download(row)} />
                      </el-icon>
                    ))}
                  </>
                );
              }
            },
          },
        },
        {
          field: 'status',
          title: '超时状态',
          width: 100,
          search: { el: 'select', props: { clearable: true } },
          slots: {
            default: ({ row }) => {
              return (
                <ElTag type={row.auditDesc == 'time_out' ? 'danger' : 'primary'}>
                  {row.auditDesc == 'time_out' ? '已超时' : '正常'}
                </ElTag>
              );
            },
          },
        },
        {
          field: 'code',
          title: '微信图片附件',
          showOverflow: 'tooltip',
          width: 100,
          slots: {
            default: ({ row, rowIndex }) => {
              if (row.images && row.images.length > 0) {
                return (
                  <>
                    <div className="flex justify-center">
                      <ElButton onClick={() => preview(row, 'images')} link type="primary">
                        查看
                      </ElButton>
                    </div>
                  </>
                );
              }
            },
          },
        },
        {
          field: 'code',
          title: '短信图片附件',
          showOverflow: 'tooltip',
          width: 100,
          slots: {
            default: ({ row, rowIndex }) => {
              if (row.notes && row.notes.length > 0) {
                return (
                  <>
                    <div className="flex justify-center">
                      <ElButton onClick={() => preview(row, 'notes')} link type="primary">
                        查看
                      </ElButton>
                    </div>
                  </>
                );
              }
            },
          },
        },
        {
          field: 'code',
          title: '其他图片附件',
          showOverflow: 'tooltip',
          width: 100,
          slots: {
            default: ({ row, rowIndex }) => {
              if (row.others && row.others.length > 0) {
                return (
                  <>
                    <div className="flex justify-center">
                      <ElButton onClick={() => preview(row, 'others')} link type="primary">
                        查看
                      </ElButton>
                    </div>
                  </>
                );
              }
            },
          },
        },
        {
          field: 'code',
          title: '操作',
          width: 80,
          slots: {
            default: ({ row, rowIndex }) => {
              return (
                <>
                  <ElButton type="primary" onClick={() => callTelephone(row, 'audit')}>
                    审核
                  </ElButton>
                </>
              );
            },
          },
        },
      ],
      onCheckboxChange: onCheckboxChange,
    };
  });
  const query = () => ProTableRef.value?.search();

  onMounted(() => {
    query();
  });
</script>
<style lang="scss" scoped>
  .expand-box {
    background: #fff;
    padding: 10px;
    .expand-table {
      color: #000;
      table {
        width: 100%;
        margin-top: 10px;
        border-collapse: collapse;
      }
      td {
        border: 1px solid rgba(5, 5, 5, 0.06);
        background: #fff;
        padding: 8px;
        width: 240px;
        &.label {
          background: #f5f7f9;
        }
      }
    }
  }
</style>
