<template>
  <el-drawer
    v-model="showModal"
    title="拨打跟进记录"
    @close="showModal = false"
    :size="850"
    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.name }}</span>
          </div>
          <div>
            <span class="text-gray-400">与案人关系：</span>
            <span>{{ currentInfo.kinship }}</span>
          </div>
          <div>
            <span class="text-gray-400">联系号码：</span>
            <span>{{ currentInfo.phone }}</span>
          </div>
          <div>
            <span class="text-gray-400">号码状态：</span>
            <span>
              <el-radio-group v-model="currentInfo.status">
                <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"
          ref="ProTableRef"
          :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="trackTime">
                  <el-date-picker
                    v-model="form.trackTime"
                    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"
                      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" @click="changeLastTime('tomorrow')">明天</el-button>
                      <el-button size="small" @click="changeLastTime('tomorrowDay')"
                        >后天</el-button
                      >
                      <el-button size="small" @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="跟进结果："
                  required
                  prop="name"
                  label-position="top"
                >
                  <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}`"
                        @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" required>
                  <el-button
                    size="small"
                    style="margin-left: 0"
                    class="mr-2 mb-2"
                    :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="remark" style="display: block">
                  <el-input
                    v-model="form.remark"
                    class="w-full"
                    :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-upload
                class="avatar-uploader"
                :action="url"
                ref="lypictureRef"
                :headers="{timeout:180000}"
                :on-success="handleFileSuccess"
                :on-remove="handleRemove"
                :auto-upload="true"
              >
                <el-button type="primary" plain :icon="Upload">上传录音文件</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"
                ref="wxpictureRef"
                class="mypicture"
                :on-preview="handlePictureCardPreview"
                :on-success="handleFileSuccess1"
                :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"
                ref="msgpictureRef"
                class="mypicture"
                :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"
                ref="otherpictureRef"
                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">确定</el-button>
      </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 } from 'vue';
  import { reactive, ref } from 'vue';
  import { ElInputNumber, ElMessage, ElTag } from 'element-plus';
  import { Upload } from '@element-plus/icons-vue';
  import { getAppEnvConfig } from '@/utils/env';
  import { saveTrackRecord } from '@/api/property';
  import { useDict } from '@/hooks/useDict';
  import { useAuthStore } from '@/stores/modules/auth';
  const { authButtonListGet } = useAuthStore(); // 获取用户权限列表
  const { PhoneResultStatus, ReduceType, FlowStatus, FollowStatus, AuditStatus, CaseStatus } = useDict("PhoneResultStatus","ReduceType", "FlowStatus", "FollowStatus","AuditStatus", "CaseStatus");
  const envs = getAppEnvConfig();
  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 ProTableRef = ref();
  const wxpictureRef = ref();
  const msgpictureRef = ref();
  const otherpictureRef = ref();
  const lypictureRef = ref();
  const dialogImageUrl = ref('');
  const dialogVisible = ref(false);
  const emits = defineEmits(['success']);
  const props = defineProps({
    mergerCase: String,
  });
  const rules = ref({
    trackTime: { required: true, message: '请选择跟进时间', trigger: 'blur' },
    remark: { required: true, message: '请输入跟进备注', trigger: 'blur' }
  });
  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({
    images: [],
    notes: [],
    phoneResultStatus: 'later',
    others: [],
    voices: [],
    remark: '',
    trackTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    nextTime: null,
  });
  const currentDetail = ref({});
  const currentInfo = ref({ name: 0, kinship: 0, phone: 0, status: '' });
  const onHide = (done) => {
    done();
  };
  const selectdList = ref([]);
  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) => {
    form.voices.push({
      url: response.message,
      name: file.name,
    });
  };
  const handleFileSuccess1 = (response, file, fileList) => {
    form.images.push({
      url: response.message,
      name: file.name,
    });
  };
  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);
    form.notes.push({
      url: response.message,
      name: file.name,
    });
  };
  const handleRemove2 = (uploadFile, uploadFiles) => {
    const index = form.notes.findIndex((v) => v.name === uploadFile.name);
    form.notes.splice(index, 1);
  };
  const handleFileSuccess3 = (response, file, fileList) => {
    form.others.push({
      url: response.message,
      name: file.name,
    });
  };
  const handleRemove3 = (uploadFile, uploadFiles) => {
    const index = form.others.findIndex((v) => v.name === uploadFile.name);
    form.others.splice(index, 1);
  };
  const onCheckboxAll = (flag) => {
    if (flag.checked) {
      selectdList.value = flag.records;
    } else {
      selectdList.value = [];
    }
  };
  const config = reactive({
    minHeight: 200,
    checkboxConfig: {
      checkMethod: ({ row }) => {
        return row.repayStatus !== 'over';
      },
    },
    columns: [
      { type: 'checkbox', width: 60, fixed: 'left' },
      {
        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('allcation_for_tenant'),
      //   showOverflow: 'tooltip',
      //   width: 120,
      //   slots: {
      //     default: ({ row }) => {
      //       return <ElTag>{row.mergerCase == 'Y' ? '是' : '否'}</ElTag>;
      //     },
      //   },
      // },
      {
        field: 'loanPlatform.name',
        title: '借款平台',
        width: 120,
        showOverflow: 'tooltip',
      },
      {
        field: 'commissionAmount',
        title: '委案金额',
        width: 120,
        showOverflow: 'tooltip',
      },
      {
        field: 'sumReductionAmount',
        title: '累计减免金额',
        width: 120,
        showOverflow: 'tooltip',
      },
      {
        field: 'sumRepayAmount',
        title: '累计还款金额',
        width: 120,
        showOverflow: 'tooltip',
      },
      {
        field: 'remainingAmount',
        title: '剩余待还金额',
        width: 120,
        showOverflow: 'tooltip',
      },
    ],
    onCheckboxChange: onCheckboxChange,
    onCheckboxAll: onCheckboxAll,
    toolbarConfig: { enabled: false },
  });
  const openModal = (info, detail, caselist) => {
    showModal.value = true;
    currentInfo.value = info;
    currentDetail.value = detail;
    form.sum = 0;
    form.phoneResultStatus = 'later';
    form.remark = '';
    form.nextTime = null;
    form.trackTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
    form.images = [];
    form.notes = [];
    form.others = [];
    form.voices = [];
    wxpictureRef.value?.clearFiles()
    msgpictureRef.value?.clearFiles()
    otherpictureRef.value?.clearFiles()
    lypictureRef.value?.clearFiles()
    resuleObj.label = '本人可联';
    resuleObj.childrenlabel = null;
    tabledata.value = caselist;
    const a = caselist.filter((v) => v.repayStatus !== 'over');
    setTimeout(() => {
      if (ProTableRef.value.element) {
        ProTableRef.value.element.setCheckboxRow(a, true);
        selectdList.value = a;
      }
    }, 500);
  };
  const submitForm = () => {
    if (!form.phoneResultStatus)
      return ElMessage.warning({
        message: '跟进状态必选',
      });
    if (!resuleObj.childrenlabel)
      return ElMessage.warning({
        message: '跟进结果必选',
      });
    if (!form.remark)
      return ElMessage.warning({
        message: '跟进备注必填',
      });
    if (!form.trackTime) {
      return ElMessage.warning({
        message: '跟进时间必选',
      });
    }
    const arr1 = selectdList.value.filter((v) => v.repayStatus === 'over');
    if (arr1.length > 0)
      return ElMessage.warning({
        message: '不可以勾选结案的案件',
        plain: true,
      });
    saveTrackRecord({
      loans: selectdList.value,
      guarantor: currentInfo.value,
      trackTime: form.trackTime,
      nextTime: form.nextTime,
      phoneResultStatus: form.phoneResultStatus,
      followStatus: resuleObj.childrenlabel,
      remark: form.remark,
      auditStatus: 'un_audit',
      voices: form.voices.map((v) => v.url)?.length > 0 ? form.voices.map((v) => v.url) : null,
      images: form.images.map((v) => v.url)?.length > 0 ? form.images.map((v) => v.url) : null,
      notes: form.notes.map((v) => v.url)?.length > 0 ? form.notes.map((v) => v.url) : null,
      others: form.others.map((v) => v.url)?.length > 0 ? form.others.map((v) => v.url) : 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: 100px;
      height: 100px;
    }
    :deep(.el-upload-list__item) {
      width: 100px;
      height: 100px;
    }
  }
</style>
