<template>
  <el-drawer
    v-model="showModal"
    title="拨打跟进记录"
    :size="850"
    @close="showModal = false"
    direction="rtl"
    :before-close="onHide"
  >
    <div class="h-full flex-col flex mydrawer pb-2">
      <div>
        <p class="font-bold mb-2">联系人信息：</p>
        <div class="flex justify-between">
          <div>
            <span class="text-gray-400">姓名：</span>
            <span>{{ currentInfo.guarantor.name }}</span>
          </div>
          <div>
            <span class="text-gray-400">与案人关系：</span>
            <span>{{ currentInfo.guarantor.kinship }}</span>
          </div>
          <div>
            <span class="text-gray-400">联系号码：</span>
            <span>{{ currentInfo.guarantor.phone }}</span>
          </div>
          <div>
            <span class="text-gray-400">号码状态：</span>
            <span>
              <el-radio-group v-model="currentInfo.guarantor.status" disabled>
                <el-radio value="N">无效</el-radio>
                <el-radio value="Y">有效</el-radio>
              </el-radio-group>
            </span>
          </div>
        </div>
      </div>
      <div>
        <ProTable :config="config" :data="tabledata" :showPagination="false" :showToolBar="false">
          <template #table_top>
            <p class="font-bold">关联案件：</p>
          </template>
        </ProTable>
      </div>
      <div class="flex">
        <div class="mt-3 pr-8 w-1/2">
          <p class="font-bold mb-2">跟进信息：</p>
          <el-form
            ref="formRef"
            inline
            :model="form"
            :rules="rules"
            label-width="110px"
            label-position="left"
          >
            <el-row>
              <el-col :span="24">
                <el-form-item class="w-full" label="跟进时间：" prop="name">
                  <el-date-picker
                    v-model="form.trackTime"
                    disabled
                    class="w-full"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    type="datetime"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item class="w-full" label="下次跟进时间：" prop="code">
                  <div>
                    <el-date-picker
                      v-model="form.nextTime"
                      disabled
                      class="w-full"
                      format="YYYY-MM-DD HH:mm:ss"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      type="datetime"
                    />
                    <div>
                      <el-button size="small" disabled @click="changeLastTime('tomorrow')"
                        >明天</el-button
                      >
                      <el-button size="small" disabled @click="changeLastTime('tomorrowDay')"
                        >后天</el-button
                      >
                      <el-button size="small" disabled @click="changeLastTime('tomorrow2Day')"
                        >2天后</el-button
                      >
                    </div>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item class="w-full" style="display: block" label="跟进结果：" prop="name">
                  <el-tabs v-model="resuleObj.label" class="w-full">
                    <el-tab-pane
                      :label="item.label"
                      :name="item.label"
                      v-for="(item, index) in tabObj"
                      :key="`tab${index}`"
                    >
                      <el-button
                        size="small"
                        :type="resuleObj.childrenlabel === item1.value ? 'primary' : null"
                        plain
                        v-for="(item1, index1) in item.children"
                        :key="`tabchild${index1}`"
                        disabled
                        @click="resuleObj.childrenlabel = item1.value"
                        >{{ item1.label }}</el-button
                      >
                    </el-tab-pane>
                  </el-tabs>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item class="w-full" style="display: block" label="跟进状态：" prop="code">
                  <el-button
                    size="small"
                    style="margin-left: 0"
                    class="mr-2 mb-2"
                    disabled
                    :type="form.phoneResultStatus === item1.value ? 'primary' : null"
                    plain
                    v-for="(item1, index1) in PhoneResultStatus"
                    :key="`btn${index1}`"
                    @click="form.phoneResultStatus = item1.value"
                    >{{ item1.label }}</el-button
                  >
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item class="w-full" label="跟进备注：" prop="code" style="display: block">
                  <el-input
                    v-model="form.remark"
                    class="w-full"
                    disabled
                    :rows="2"
                    type="textarea"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div class="w-1/2">
          <p class="font-bold mb-2 mt-2">跟进附件：</p>
          <el-form inline :model="form" :rules="rules" label-width="110px" label-position="left">
            <el-form-item class="w-full" label="通话录音：" prop="code">
              <el-icon style="cursor: pointer; margin-right: 10px">
                <Download
                  v-for="(item, index) in form.voices"
                  :key="index"
                  @click="download(item)"
                />
              </el-icon>
              <el-upload
                class="avatar-uploader"
                :action="url"
                :headers="{ timeout: 180000 }"
                :on-success="handleFileSuccess"
                :on-remove="handleRemove"
                :disabled="props.mode !== 'handle'"
                :auto-upload="true"
              >
                <el-button type="primary" plain :icon="Upload" :disabled="props.mode !== 'handle'"
                  >上传录音文件</el-button
                >
              </el-upload>
              <!-- 进度条 -->
              <!-- <el-progress v-if="progressFlag" :percentage="loadProgress" /> -->
            </el-form-item>
            <el-form-item label="微信图片附件：" prop="code" class="w-full">
              <el-upload
                :action="url"
                :headers="{ timeout: 180000 }"
                list-type="picture-card"
                v-model:file-list="form.images"
                class="mypicture"
                :on-preview="handlePictureCardPreview"
                :on-success="handleFileSuccess1"
                :disabled="props.mode !== 'handle'"
                :on-remove="handleRemove1"
              >
                <div class="text-center">
                  <el-icon><Plus /></el-icon>
                  <div>微信相关附件</div>
                </div>
              </el-upload>
            </el-form-item>
            <el-form-item label="短信图片附件：" prop="code" class="w-full">
              <el-upload
                :action="url"
                :headers="{ timeout: 180000 }"
                list-type="picture-card"
                class="mypicture"
                v-model:file-list="form.notes"
                :disabled="props.mode !== 'handle'"
                :on-preview="handlePictureCardPreview"
                :on-success="handleFileSuccess2"
                :on-remove="handleRemove2"
              >
                <div class="text-center">
                  <el-icon><Plus /></el-icon>
                  <div>短信相关附件</div>
                </div>
              </el-upload>
            </el-form-item>
            <el-form-item label="其他图片附件：" prop="code" class="w-full">
              <el-upload
                :action="url"
                :headers="{ timeout: 180000 }"
                list-type="picture-card"
                v-model:file-list="form.others"
                :disabled="props.mode !== 'handle'"
                class="mypicture"
                :on-preview="handlePictureCardPreview"
                :on-success="handleFileSuccess3"
                :on-remove="handleRemove3"
              >
                <div class="text-center">
                  <el-icon><Plus /></el-icon>
                  <div>其他相关附件</div>
                </div>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="showModal = false">取消</el-button>
        <el-button type="primary" @click="submitForm" v-if="props.mode === 'handle'"
          >确定</el-button
        >
        <template v-else>
          <el-button type="primary" @click="submitForm('passed')">通过</el-button>
          <el-button type="danger" @click="submitForm('rejected')">拒绝</el-button>
        </template>
      </div>
    </template>
    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </el-drawer>
</template>
<script setup lang="jsx" name="reduceDrawer">
  import dayjs from 'dayjs';
  import { computed, inject } from 'vue';
  import { reactive, ref } from 'vue';
  import { ElInputNumber, ElMessage, ElTag } from 'element-plus';
  import { Upload, Download } from '@element-plus/icons-vue';
  import { getAppEnvConfig } from '@/utils/env';
  import { saveTrackRecord } from '@/api/property';
  import { auditAudit } from '@/api/audit';
  const envs = getAppEnvConfig();
  const downloadfile = inject('download');
  const url = envs.VITE_GLOB_API_URL_PREFIX + '/sys/upload';
  const showModal = ref(false);
  const editFirst = ref(false);
  const tabledata = ref([]);
  const progressFlag = ref(false);
  const loadProgress = ref(0);
  const dialogImageUrl = ref('');
  const dialogVisible = ref(false);
  import { useAuthStore } from '@/stores/modules/auth';
  const { authButtonListGet } = useAuthStore(); // 获取用户权限列表

  import { useDict } from '@/hooks/useDict';
  const { PhoneResultStatus, ReduceType, FlowStatus, FollowStatus, AuditStatus, CaseStatus } =
    useDict(
      'PhoneResultStatus',
      'ReduceType',
      'FlowStatus',
      'FollowStatus',
      'AuditStatus',
      'CaseStatus'
    );
  const props = defineProps({
    mode: String,
  });
  const emits = defineEmits(['success']);
  const tabObj = [
    {
      label: '本人可联',
      children: [
        { label: '接通后挂断', value: 'hang_up' },
        { label: '接通有实质进展', value: 'progress' },
      ],
    },
    {
      label: '联系人可联',
      children: [
        { 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: '未接听',
      children: [
        { label: '无人接听', value: 'no_answer' },
        { label: '关机', value: 'Shutdown' },
        { label: '空号', value: 'dead_number' },
        { label: '占线/忙音/正在通话中', value: 'Busy' },
        { label: '停机', value: 'closing_down' },
        { label: '机器人回复', value: 'Robot_reply' },
      ],
    },
    {
      label: '非电联',
      children: [
        { label: '微信', value: 'WeChat' },
        { label: '短信', value: 'short_message' },
        { label: 'QQ', value: 'QQ' },
        { label: '飞书', value: 'fly' },
        { label: '钉钉', value: 'DING' },
      ],
    },
  ];

  const resuleObj = reactive({
    label: '本人可联',
    childrenlabel: null,
  });

  const form = reactive({
    sum: 0,
    images: [],
    notes: [],
    phoneResultStatus: '',
    others: [],
    voices: [],
    remark: '',
    trackTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    nextTime: null,
  });
  const currentInfo = ref({ name: 0, kinship: 0, phone: 0, status: '' });
  const onHide = (done) => {
    done();
  };
  const selectdList = ref([]);
  const onCheckboxAll = (flag) => {
    if (flag.checked) {
      selectdList.value = flag.records;
    } else {
      selectdList.value = [];
    }
  };
  const onCheckboxChange = (row) => {
    selectdList.value = row.records;
  };
  const handleRemove = (uploadFile, uploadFiles) => {
    const index = form.voices.findIndex((v) => v.name === uploadFile.name);
    form.voices.splice(index, 1);
  };

  const handlePictureCardPreview = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url;
    dialogVisible.value = true;
  };
  const changeLastTime = (day) => {
    if (day === 'tomorrow') {
      form.nextTime = dayjs().add(1, 'day').format('YYYY-MM-DD HH:mm:ss');
    } else if (day === 'tomorrowDay') {
      form.nextTime = dayjs().add(2, 'day').format('YYYY-MM-DD HH:mm:ss');
    } else {
      form.nextTime = dayjs().add(3, 'day').format('YYYY-MM-DD HH:mm:ss');
    }
  };
  const handleFileSuccess = (response, file, fileList) => {
    if (file.uid) {
      const item = form.voices.find((v) => v.uid === file.uid);
      item.url = envs.VITE_GLOB_API_URL_PREFIX + '/sys/static/' + response.message;
    }
  };
  const handleFileSuccess1 = (response, file, fileList) => {
    if (file.uid) {
      const item = form.images.find((v) => v.uid === file.uid);
      item.url = envs.VITE_GLOB_API_URL_PREFIX + '/sys/static/' + response.message;
    }
  };
  const handleRemove1 = (uploadFile, uploadFiles) => {
    const index = form.images.findIndex((v) => v.name === uploadFile.name);
    form.images.splice(index, 1);
  };
  const handleFileSuccess2 = (response, file, fileList) => {
    // console.log(response, file);
    if (file.uid) {
      const item = form.notes.find((v) => v.uid === file.uid);
      item.url = envs.VITE_GLOB_API_URL_PREFIX + '/sys/static/' + response.message;
    }
  };
  const handleRemove2 = (uploadFile, uploadFiles) => {
    const index = form.notes.findIndex((v) => v.name === uploadFile.name);
    form.notes.splice(index, 1);
  };
  const handleFileSuccess3 = (response, file, fileList) => {
    if (file.uid) {
      const item = form.others.find((v) => v.uid === file.uid);
      item.url = envs.VITE_GLOB_API_URL_PREFIX + '/sys/static/' + response.message;
    }
  };
  const download = (item) => {
    downloadfile(item.url.replace(envs.VITE_GLOB_API_URL_PREFIX, ''), {}, item.name);
  };
  const handleRemove3 = (uploadFile, uploadFiles) => {
    const index = form.others.findIndex((v) => v.name === uploadFile.name);
    form.others.splice(index, 1);
  };
  const config = reactive({
    minHeight: 200,
    columns: [
      // { type: 'checkbox', width: 60 },
      {
        field: 'caseId',
        title: '案件ID',
        width: 230,
        slots: {
          default: ({ row, rowIndex }) => {
            return (
              <>
                <div className="inline-block">{row.caseId}</div>
                <Tag row={row} />
              </>
            );
          },
        },
        showOverflow: 'tooltip',
      },
      {
        field: 'mergerCase',
        title: '是否共案处理',
        visible: authButtonListGet.includes('show_merger_case'),
        showOverflow: 'tooltip',
        width: 120,
        slots: {
          default: ({ row }) => {
            return <ElTag>{row.mergerCase == 'Y' ? '是' : '否'}</ElTag>;
          },
        },
      },
      {
        field: 'loanPlatform.name',
        showOverflow: 'tooltip',
        width: 120,
        title: '借款平台',
      },
      {
        field: 'commissionAmount',
        showOverflow: 'tooltip',
        width: 120,
        title: '委案金额',
      },
      {
        field: 'sumReductionAmount',
        showOverflow: 'tooltip',
        width: 120,
        title: '累计减免金额',
      },
      {
        field: 'sumRepayAmount',
        showOverflow: 'tooltip',
        width: 120,
        title: '累计还款金额',
      },
      {
        field: 'remainingAmount',
        showOverflow: 'tooltip',
        width: 120,
        title: '剩余待还金额',
      },
    ],
    onCheckboxChange: onCheckboxChange,
    onCheckboxAll: onCheckboxAll,
    toolbarConfig: { enabled: false },
  });
  const openModal = (info) => {
    showModal.value = true;
    currentInfo.value = info;
    form.trackTime = info.trackTime;
    form.remark = info.remark;
    form.phoneResultStatus = info.phoneResultStatus;
    resuleObj.childrenlabel = info.followStatus;
    form.nextTime = info.nextTime;
    form.notes = info.notes
      ? info.notes.map((v) => ({
          name: v.slice(v.lastIndexOf('/') + 1, v.length),
          url: envs.VITE_GLOB_API_URL_PREFIX + '/sys/static/' + v,
        }))
      : [];
    form.voices = info.voices
      ? info.voices.map((v) => ({
          name: v.slice(v.lastIndexOf('/') + 1, v.length),
          url: envs.VITE_GLOB_API_URL_PREFIX + '/sys/static/' + v,
        }))
      : [];
    form.images = info.images
      ? info.images.map((v) => ({
          name: v.slice(v.lastIndexOf('/') + 1, v.length),
          url: envs.VITE_GLOB_API_URL_PREFIX + '/sys/static/' + v,
        }))
      : [];
    form.others = info.others
      ? info.others.map((v) => ({
          name: v.slice(v.lastIndexOf('/') + 1, v.length),
          url: envs.VITE_GLOB_API_URL_PREFIX + '/sys/static/' + v,
        }))
      : [];
    tabledata.value = info.loans;
    console.log('formform', form);
  };
  const submitForm = (type) => {
    let voices = JSON.parse(JSON.stringify(form.voices.map((v) => v.url)));
    let images = JSON.parse(JSON.stringify(form.images.map((v) => v.url)));
    let notes = JSON.parse(JSON.stringify(form.notes.map((v) => v.url)));
    let others = JSON.parse(JSON.stringify(form.others.map((v) => v.url)));
    voices = voices.map((v) => {
      return v.replace(envs.VITE_GLOB_API_URL_PREFIX + '/sys/static/', '');
    });
    images = images.map((v) => {
      return v.replace(envs.VITE_GLOB_API_URL_PREFIX + '/sys/static/', '');
    });
    notes = notes.map((v) => {
      return v.replace(envs.VITE_GLOB_API_URL_PREFIX + '/sys/static/', '');
    });
    others = others.map((v) => {
      return v.replace(envs.VITE_GLOB_API_URL_PREFIX + '/sys/static/', '');
    });
    saveTrackRecord({
      loans: tabledata.value,
      id: currentInfo.value.id,
      guarantor: currentInfo.value.guarantor,
      trackTime: form.trackTime,
      nextTime: form.nextTime,
      phoneResultStatus: form.phoneResultStatus,
      auditStatus: type === 'rejected' ? 'rejected' : type === 'passed' ? 'passed' : 'complete',
      followStatus: resuleObj.childrenlabel,
      remark: form.remark,
      voices: voices.length > 0 ? voices : null,
      images: images.length > 0 ? images : null,
      notes: notes.length > 0 ? notes : null,
      others: others.length > 0 ? others : null,
    }).then((res) => {
      if (res.success) {
        ElMessage.success({
          message: '保存成功',
          plain: true,
        });
        showModal.value = false;
        emits('success');
      }
    });
  };
  defineExpose({
    openModal,
  });
</script>
<style lang="scss" scoped>
  .mydrawer {
    :deep(.card) {
      padding: 0;
      border: none;
    }
    :deep(.el-date-editor) {
      width: 100%;
    }
    .el-form-item {
      margin-right: 0;
    }
  }
  .mypicture {
    :deep(.el-upload--picture-card) {
      width: 80px;
      height: 80px;
    }
    :deep(.el-upload-list__item) {
      width: 80px;
      height: 80px;
    }
    :deep(.el-upload--picture-card) {
      font-size: 12px;
    }
  }
</style>
