<template>
  <div class="safety-platform-container">
    <el-alert
      v-if="showAlertBar"
      title="您提交的反馈材料审核不通过，请尽快查看并修改，再次提交进行审核，谢谢！"
      type="warning"
    />
    <div class="back"><BreadcrumbBack /> 安全责任书签署 </div>
    <header class="safety-platform-container__header">
      <div class="breadcrumb-title">{{ formData?.responsibilityName }} </div>
      <div class="detail-content">
        <span>类别名称：{{ formData?.departmentName }} </span>
        <span>创建人：{{ formData?.createdByName }} </span>
        <span>创建时间：{{ formData?.createdAt }} </span>
      </div>
    </header>

    <main class="safety-platform-container__main">
      <el-form ref="formRef" label-width="auto" :model="formData" :rules="rules">
        <h4>基本信息</h4>
        <div class="detail-ct">
          <div class="row">
            <div class="col">
              <div class="label">责任书名称：</div>
              <div class="value">{{ formData.responsibilityName }}</div>
            </div>
            <div class="col">
              <div class="label">状态：</div>
              <div class="value">{{ formData.statusName }}</div>
            </div>
          </div>
          <div class="row">
            <div class="col">
              <div class="label">签署人数：</div>
              <div class="value">{{ formData.signedQuantity }}</div>
            </div>
            <div class="col">
              <div class="label">下发数：</div>
              <div class="value">{{ formData.issueQuantity }}</div>
            </div>
          </div>
          <div class="row">
            <div class="col">
              <div class="label">计划开始日期：</div>
              <div class="value">{{ formData.planStartTime }}</div>
            </div>
            <div class="col">
              <div class="label">计划结束日期：</div>
              <div class="value">{{ formData.planEndTime }}</div>
            </div>
          </div>
        </div>
        <h4>责任书内容</h4>
        <div class="detail-ct">
          <div class="row">
            <div class="col">
              <div class="label">责任书文档：</div>
              <div class="value value-s1">
                <div class="file-list">
                  <div class="file-item" v-for="item in formData.attachment" :key="item.fileId">
                    <span class="file-item--name">{{ item.fileName }}</span>
                    <div class="file-item--footer">
                      <!-- <div class="info">
                        <span>{{ item.fileSize }}</span>
                      </div> -->
                      <el-button link type="primary" @click="previewOnline(item.fileUrl, item.fileType)"
                        >预览</el-button
                      >
                      <el-button link type="primary" @click.stop="downloadFile(item.fileUrl, item.fileName)"
                        >下载</el-button
                      >
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <template v-if="signRecords.level1.length">
          <h4 v-if="currentDepartmentKey === 'A'"> 副院长签署 </h4>
          <h4 v-if="currentDepartmentKey === 'B'"> 负责人签署 </h4>
          <h4 v-if="currentDepartmentKey === 'C'"> 负责人签署 </h4>
          <h4 v-if="currentDepartmentKey === 'D'"> 科室负责人签署 </h4>
          <div class="detail-ct">
            <div class="row" v-for="item in signRecords.level1" :key="item.id">
              <div class="col">
                <div class="label">签名：</div>
                <div class="value value-s1">
                  <el-form-item>
                    <UploadFiles
                      :disabled="!item.signFlag"
                      accept=".jpeg,.jpg,.png,.svg"
                      label="上传文件"
                      :fileList="item.attachment"
                      @upload-success="(fileList) => handleUploadSignsUploadSuccess(item, fileList)"
                    />
                  </el-form-item>
                  <div class="file-list">
                    <div class="file-item" v-for="file in item.attachment" :key="file.fileId">
                      <span class="file-item--name">{{ file.fileName }}</span>
                      <div class="file-item--footer">
                        <el-button link type="primary" @click="previewOnline(file.fileUrl, file.fileType)"
                          >预览</el-button
                        >
                        <el-button link type="primary" @click.stop="downloadFile(file.fileUrl, file.fileName)"
                          >下载</el-button
                        >
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </template>
        <template v-if="signRecords.level2.length">
          <h4 v-if="currentDepartmentKey === 'A'"> 党委书记签署 </h4>
          <h4 v-if="currentDepartmentKey === 'B'"> 党委书记签署 </h4>
          <h4 v-if="currentDepartmentKey === 'C'"> 党委书记签署</h4>
          <h4 v-if="currentDepartmentKey === 'D'"> 部门负责人签署 </h4>
          <div class="detail-ct">
            <div class="row" v-for="item in signRecords.level2" :key="item.id">
              <div class="col">
                <div class="label">签名：</div>
                <div class="value value-s1">
                  <el-form-item>
                    <UploadFiles
                      :disabled="!item.signFlag"
                      accept=".jpeg,.jpg,.png,.svg"
                      label="上传文件"
                      :fileList="item.attachment"
                      @upload-success="(fileList) => handleUploadSignsUploadSuccess(item, fileList)"
                    />
                  </el-form-item>
                  <div class="file-list">
                    <div class="file-item" v-for="file in item.attachment" :key="file.fileId">
                      <span class="file-item--name">{{ file.fileName }}</span>
                      <div class="file-item--footer">
                        <el-button link type="primary" @click="previewOnline(file.fileUrl, file.fileType)"
                          >预览</el-button
                        >
                        <el-button link type="primary" @click.stop="downloadFile(file.fileUrl, file.fileName)"
                          >下载</el-button
                        >
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </template>
        <template v-if="signRecords.level3.length">
          <h4 v-if="currentDepartmentKey === 'A'"> 院长签署 </h4>
          <h4 v-if="currentDepartmentKey === 'B'"> 院长签署 </h4>
          <h4 v-if="currentDepartmentKey === 'C'"> 所长签署 </h4>
          <div class="detail-ct">
            <div class="row" v-for="item in signRecords.level3" :key="item.id">
              <div class="col">
                <div class="label">签名：</div>
                <div class="value value-s1">
                  <el-form-item>
                    <UploadFiles
                      :disabled="!item.signFlag"
                      accept=".jpeg,.jpg,.png,.svg"
                      label="上传文件"
                      :fileList="item.attachment"
                      @upload-success="(fileList) => handleUploadSignsUploadSuccess(item, fileList)"
                    />
                  </el-form-item>
                  <div class="file-list">
                    <div class="file-item" v-for="file in item.attachment" :key="file.fileId">
                      <span class="file-item--name">{{ file.fileName }}</span>
                      <div class="file-item--footer">
                        <el-button link type="primary" @click="previewOnline(file.fileUrl, file.fileType)"
                          >预览</el-button
                        >
                        <el-button link type="primary" @click.stop="downloadFile(file.fileUrl, file.fileName)"
                          >下载</el-button
                        >
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </template>
      </el-form>
    </main>
    <footer class="safety-platform-container__footer">
      <el-button @click="back">返回</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submiting">提交</el-button>
    </footer>
  </div>
  <PreviewOnline ref="previewOnlineRef" />
  <el-dialog v-model="dialogVisible" title="下一节点签署人" width="500">
    <el-form-item :label="currentLabel">
      <el-select
        v-model="signerId"
        placeholder="请选择"
        size="large"
        style="width: 100%"
        filterable
        remote
        :remote-method="remoteMethod"
      >
        <el-option v-for="item in userOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
    </el-form-item>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleDialogCancel">取消</el-button>
        <el-button type="primary" @click="handleDialogConfirm"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
  import { onMounted, ref, computed, reactive } from 'vue';
  import { ElMessage } from 'element-plus';
  import '@wangeditor/editor/dist/css/style.css';
  import { useRouter, useRoute } from 'vue-router';
  import { downloadFile } from '@/views/disaster/utils';

  import UploadFiles from '@/components/UploadFiles/UploadFiles.vue';
  import {
    safetyResponsibilityDeptQueryDetail,
    // safetyResponsibilityDeptSignOrFeedback,
    safetyResponsibilityDeptBatchSign,
    safetyResponsibilityDeptSaveSign,
    queryAvailableUserList,
  } from '@/api/production-safety/responsibility-implementation';

  import { unformatAttachment, formatAttachmentList } from '@/components/UploadFiles/utils';
  import PreviewOnline from '@/views/disaster/components/PreviewOnline.vue';

  const uploadImagesRef = ref<InstanceType<typeof UploadFiles>>();
  const router = useRouter();
  const route = useRoute();
  const formRef = ref<any>(null);
  const submiting = ref(false);
  const dialogVisible = ref(false);

  const formData = reactive<any>({
    departmentName: '',
    createdByName: '',
    createdAt: '',
    attachment: [],
    feedback: [],
    signsUpload: [],
    responsibilityName: '',
    statusName: '',
    issueQuantity: '',
    signedQuantity: '',
    userGroupName: '',
    planStartTime: null,
    planEndTime: null,
    rejection: '',
    signRecords: [],
  });

  const rules = reactive({
    signsUpload: [
      {
        required: true,
        message: '请上传签署材料',
      },
    ],
  });

  const signRecords = computed(() => {
    return {
      level1: formData.signRecords.filter((item) => item.signLevel === 1),
      level2: formData.signRecords.filter((item) => item.signLevel === 2),
      level3: formData.signRecords.filter((item) => item.signLevel === 3),
    };
  });

  const currentDepartmentKey = computed(() => {
    switch (formData.departmentName.trim()) {
      case '院领导':
        return 'A';
      case '所/中心/职能部门/直属研究部/分公司':
        return 'B';
      case '所/中心级部门':
        return 'C';
      case '科室':
        return 'D';
      case '员工':
      case '常驻供应商':
        return 'E';
      default:
        return '';
    }
  });

  const userOptions = ref<any[]>([]);

  const showAlertBar = computed(() => {
    if (!formData.rejection) {
      return false;
    }
    return route.query.status === '3' && formData.rejection !== null;
  });
  const previewOnlineRef = ref<InstanceType<typeof PreviewOnline>>();
  const signerId = ref('');
  const currentLabel = ref('');
  const previewOnline = (url: string | undefined, type) => {
    if (url) {
      previewOnlineRef.value?.open(url, type);
    }
  };
  const handleUploadSignsUploadSuccess = async (item, fileList) => {
    const attachment = await formatAttachmentList(fileList);
    item.attachment = attachment;

    formData.signRecords = [...signRecords.value.level1, ...signRecords.value.level2, ...signRecords.value.level3];
  };
  const back = () => {
    router.push({
      name: 'responsibilityAgreeManageDept',
    });
  };
  const handleSubmit = () => {
    formRef.value?.validate(async (valid) => {
      if (valid) {
        const fullAttachment = formData.signRecords.every((item) => item.attachment || item.attachment?.length > 0);
        const signList = formData.signRecords.filter((item) => item.signFlag && item.signStatus === 0);
        const firstSignItem = signList?.[0] ?? {};
        const lastSignItem = signList?.[signList.length - 1] ?? {};
        const isEmptyAttachment = !firstSignItem?.attachment || firstSignItem?.attachment?.length === 0;
        const currentLevel = lastSignItem?.signLevel;
        const currentOrder = lastSignItem?.signOrder;
        const nextLevel = Math.min(currentLevel + 1, 3);
        const nextOrder = currentOrder + 1;

        //需要弹框选择用户的部门类型(C和D)
        const specialDeptKey = /C|D/.test(currentDepartmentKey.value);

        if (specialDeptKey) {
          if (!fullAttachment || isEmptyAttachment) {
            ElMessage.warning('请上传签署材料');
            return;
          }

          // if (signerId.value) {
          //             // handleSubmitSign(firstSignItem).then(() => {
          //             //   handleSafetyResponsibilityDeptSaveSign(signerId.value, nextLevel, nextOrder);
          //             // });
          //           } else

          if (currentLevel === 2 && currentDepartmentKey.value === 'D') {
            handleSubmitSign(firstSignItem);
          } else if (currentLevel === 3 && currentDepartmentKey.value === 'C') {
            handleSubmitSign(firstSignItem);
          } else {
            // if (isEmptyAttachment) {
            //   ElMessage.warning('请上传签署材料');
            //   return;
            // }
            if (currentDepartmentKey.value === 'C' && currentLevel < 3) {
              currentLabel.value = currentLevel === 1 ? '党委书记' : '所长';
            }
            if (currentDepartmentKey.value === 'D' && currentLevel < 2) {
              currentLabel.value = '部门负责人';
            }
            dialogVisible.value = true;
          }
        }
        // 非C和D的部门类型
        else {
          if (isEmptyAttachment) {
            ElMessage.warning('请上传签署材料');
            return;
          }
          handleSubmitSign(firstSignItem);
        }
      }
    });
  };

  const handleSafetyResponsibilityDeptSaveSign = (signerId, nextLevel, nextOrder) => {
    submiting.value = true;
    const params = {
      signStatus: 0,
      signLevel: nextLevel,
      contractId: route.query.id,
      signerId,
      signOrder: nextOrder,
    };
    return safetyResponsibilityDeptSaveSign(params)
      .then(() => {})
      .catch(() => {})
      .finally(() => {
        submiting.value = false;
      });
  };

  const handleSubmitSign = (firstItem) => {
    submiting.value = true;
    const params = {
      ids: [route.query.id],
      attachment: JSON.stringify(firstItem?.attachment),
    };

    return safetyResponsibilityDeptBatchSign(params)
      .then((res) => {
        router.push({
          name: 'responsibilityAgreeManageDept',
        });
        ElMessage.success('责任书签署成功');
      })
      .finally(() => {
        submiting.value = false;
      });
  };
  // 下一节点签署人 保存
  const handleDialogConfirm = async () => {
    const fullAttachment = formData.signRecords.every((item) => item.attachment || item.attachment?.length > 0);
    const signList = formData.signRecords.filter((item) => item.signFlag && item.signStatus === 0);
    const firstSignItem = signList?.[0] ?? {};
    const lastSignItem = signList?.[signList.length - 1] ?? {};
    const isEmptyAttachment = !firstSignItem?.attachment || firstSignItem?.attachment?.length === 0;
    const currentLevel = lastSignItem?.signLevel;
    const currentOrder = lastSignItem?.signOrder;
    const nextLevel = Math.min(currentLevel + 1, 3);
    const nextOrder = currentOrder + 1;
    if (signerId.value) {
      const params = {
        sign: {
          signStatus: 0,
          signLevel: nextLevel,
          contractId: route.query.id,
          signOrder: nextOrder,
        },
        signerId: signerId.value || null,
        ids: [route.query.id],
        attachment: JSON.stringify(firstSignItem?.attachment),
      };
      safetyResponsibilityDeptBatchSign(params)
        .then(() => {
          ElMessage.success('责任书签署成功');
          router.push({
            name: 'responsibilityAgreeManageDept',
          });
        })
        .finally(() => {
          submiting.value = false;
        });
      dialogVisible.value = false;
    } else {
      ElMessage.warning('请选择签署人');
    }
  };

  const handleDialogCancel = () => {
    dialogVisible.value = false;
    signerId.value = '';
  };

  const handleQueryDetail = () => {
    safetyResponsibilityDeptQueryDetail({
      id: route.query.id,
    }).then((res) => {
      Object.keys(formData).forEach((name) => {
        if (name in res) {
          Object.assign(formData, {
            [name]: res[name],
            attachment: unformatAttachment(res.attachment),
            signsUpload: unformatAttachment(res.signsUpload),
            feedback: unformatAttachment(res.feedback),
            signRecords: res.signRecords?.map((item) => ({
              ...item,
              attachment: unformatAttachment(item.attachment),
            })),
          });
        }
      });
    });
  };
  const remoteMethod = async (value) => {
    await getUserData(value);
  };
  const getUserData = (realname = '') => {
    queryAvailableUserList({
      pageNumber: 1,
      pageSize: 300,
      queryParam: { realname },
    }).then((res: any) => {
      userOptions.value = (res.records || [])?.map((u: any) => ({
        value: u.id,
        label: u.realname,
      }));
    });
  };

  onMounted(async () => {
    await getUserData('');
    handleQueryDetail();
  });
</script>

<style lang="scss" scoped>
  @use '@/styles/page-main-layout.scss' as *;
  @use '@/styles/page-details-layout.scss' as *;
  @use '@/styles/basic-table-action.scss' as *;
  h4 {
    margin-bottom: 10px;
  }
  .detail-content {
    display: flex;
    gap: 30px;
    margin: 10px 0;
    font-size: 14px;
  }
  .detail-ct {
    display: flex;
    flex-direction: column;
    border: 1px solid rgb(220, 223, 230);
    font-size: 14px;
    margin-bottom: 25px;
    .row {
      display: flex;

      border-bottom: 1px solid rgb(220, 223, 230);
    }
    .row:last-child {
      border-bottom: none;
    }
    .col {
      display: flex;
      flex: 1;
      min-height: 40px;
      align-items: stretch;
      .label {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        width: 160px;
        background-color: rgb(245, 247, 250);
        border-right: 1px solid rgb(220, 223, 230);
      }

      .value {
        display: flex;
        justify-content: space-between;
        flex: 1;
        padding: 10px 20px;
        align-items: center;
        border-right: 1px solid rgb(220, 223, 230);
      }
      .value-s1 {
        min-height: 60px;
      }
      .value:nth-child(2) {
        border-right: 0;
      }
    }
    .col:nth-child(2) .label {
      border-left: 1px solid rgb(220, 223, 230);
    }
  }
  .table {
    display: flex;
    align-items: stretch;
    border: 1px solid rgb(220, 223, 230);
    border-width: 1px 1px 0 1px;
  }
  .table .value {
    display: flex;
    align-items: center;
    // (:deep).el-form-item {
    //   margin-bottom: 0;
    // }
  }
  .table .label {
    display: flex;
    align-items: center;
    border-right: 1px solid rgb(220, 223, 230);
    background-color: rgb(245, 247, 250);
  }
  .back {
    display: flex;
    align-items: center;
    gap: 16px;
    background-color: white;
    padding: 16px 22px;
    font-size: 20px;
    font-weight: 600;
    color: rgba(0, 0, 0, 0.85);
  }
  // :deep(.breadcrumb .title) {
  //   margin-left: 0;
  // }

  // .main {
  //   display: flex;
  //   flex-direction: column;
  //   padding: 20px;
  //   flex: 1;
  //   overflow: hidden;
  //   background-color: #fff;
  // }
  // .button-content {
  //   margin-bottom: 20px;
  // }

  // .page-content {
  //   display: flex;
  //   justify-content: flex-end;
  // }
  // // :deep(.el-form) {
  // //   flex: 1;
  // //   overflow: hidden;
  // //   overflow-y: auto;
  // // }
</style>
