<template>
  <div class="safety-platform-container">
    <header class="safety-platform-container__header">
      <div class="breadcrumb-title"><BreadcrumbBack /> {{ formData?.responsibilityName }} </div>
      <div class="detail-content">
        <span>类别名称：{{ formData?.departmentName }} </span>
        <span>创建人：{{ formData?.createdByName }} </span>
        <span>创建时间：{{ formData?.createdAt }} </span>
      </div>
    </header>
    <el-alert v-if="showAlertBar" :title="formData.rejection" type="warning" />

    <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.userGroupName }}</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 || $route.query.mode === 'view'"
                      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 || $route.query.mode === 'view'"
                      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 || $route.query.mode === 'view'"
                      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>

        <h4>材料上传</h4>

        <div class="detail-ct">
          <div class="row">
            <div class="col">
              <div class="label">上传附件：</div>
              <div class="value value-s1">
                <el-form-item prop="feedback">
                  <UploadFiles
                    :disabled="$route.query.mode === 'view'"
                    label="上传附件"
                    @upload-success="(fileList) => handleUploadSuccess('feedback', fileList)"
                    :fileList="formData.feedback"
                  />
                </el-form-item>
                <div class="file-list" v-if="formData.feedback?.length">
                  <div class="file-item" v-for="item in formData.feedback" :key="item.fileId">
                    <span class="file-item--name">{{ item.fileName }}</span>
                    <div class="file-item--footer">
                      <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>
      </el-form>
    </main>
    <footer class="safety-platform-container__footer">
      <el-button @click="$router.push({ name: 'responsibilityAgreeManageDept' })">返回</el-button>
      <el-button v-if="$route.query.mode !== 'view'" type="primary" @click="handleSubmit" :loading="submiting"
        >提交</el-button
      >
    </footer>
  </div>
  <PreviewOnline ref="previewOnlineRef" />
</template>
<script lang="ts" setup>
  import { onMounted, ref, computed, reactive } from 'vue';
  import { ElMessage } from 'element-plus';
  // @ts-ignore: missing type declarations for CSS side-effect import
  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,
    queryAvailableUserList,
    safetyResponsibilityDeptSignOrFeedback,
  } from '@/api/production-safety/responsibility-implementation';

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

  const router = useRouter();
  const route = useRoute();
  const formRef = ref<any>(null);
  const submiting = ref(false);

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

  const rules = reactive({
    signsUpload: [
      {
        required: true,
        message: '请上传签署材料',
      },
    ],
    feedback: [
      {
        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 formData.status !== 5 && formData.rejection !== null;
  });
  const previewOnlineRef = ref<InstanceType<typeof PreviewOnline>>();

  const previewOnline = (url: string | undefined, type) => {
    if (url) {
      previewOnlineRef.value?.open(url, type);
    }
  };
  const handleUploadSignsUploadSuccess = (item, fileList) => {
    item.attachment = fileList;
    formData.signRecords = [...signRecords.value.level1, ...signRecords.value.level2, ...signRecords.value.level3];
  };

  const handleUploadSuccess = (prop, fileList) => {
    formData[prop] = fileList;
    formRef.value.validateField(prop);
  };

  const handleSubmit = async () => {
    const params = {
      updateType: 1,
      id: route.query.id,
      feedback: JSON.stringify(await formatAttachmentList(formData.feedback)),
    };
    console.log('params:', params);
    formRef.value?.validate((valid) => {
      if (valid) {
        submiting.value = true;
        safetyResponsibilityDeptSignOrFeedback(params)
          .then((res) => {
            ElMessage.success('提交成功');
            router.push({ name: 'responsibilityAgreeManageDept' });
          })
          .finally(() => {
            submiting.value = false;
          });
      }
    });
  };

  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 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);
  }

  .file-list {
    display: flex;
    flex-direction: column;
    gap: 10px;
    width: 50%;
    .file-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px;
      // border: 1px solid rgb(220, 223, 230);

      .file-item--name {
        font-size: 14px;
        color: #606266;
      }

      .file-item--footer {
        display: flex;
        align-items: center;
        gap: 10px;

        .info {
          font-size: 12px;
          color: #9099a4;
        }
      }
    }
  }

  // :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>
