<template>
  <div class="safety-platform-container">
    <el-alert v-if="showAlertBar" :title="formData?.rejection" type="warning" />
    <div class="back"><BreadcrumbBack /> 安全责任通知管理反馈 </div>
    <!-- <div class="hint">您提交的反馈材料审核不通过，请尽快查看并修改，再次提交进行审核，谢谢！{{ formData?.rejection }}</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>

    <!-- v-if="showAlertBar" -->
    <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 class="row">
            <div class="col">
              <div class="label">责任通知内容：</div>
              <div class="value value-s1">
                <div class="file-list">
                  <div class="file-item">
                    <div v-html="formData.content"></div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <template v-if="isSignsUpload">
          <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="signsUpload">
                    <UploadFiles
                      label="上传附件"
                      @uploadSuccess="handleUploadSignsUploadSuccess"
                      :fileList="formData.signsUpload"
                    />
                  </el-form-item>
                  <!-- <div class="file-list" v-if="formData.signsUpload.length">
                  <div class="file-item" v-for="item in formData.signsUpload" :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>
        </template>
        <template v-else>
          <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
                      label="上传附件"
                      @uploadSuccess="handleUploadFeedbackUploadSuccess"
                      :fileList="formData.feedback"
                    />
                  </el-form-item>
                  <!-- <div class="file-list" v-if="formData.signsUpload.length">
                  <div class="file-item" v-for="item in formData.signsUpload" :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>
        </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" />
</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 {
    safetyNoticeDeptQueryDetail,
    safetyNoticeDeptFeedback,
  } 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: 0,
    userGroupName: '',
    planStartTime: null,
    planEndTime: null,
    rejection: '',
    status: null,
  });

  const rules = reactive({
    signsUpload: [
      {
        required: true,
        message: '请上传签署材料',
      },
    ],
  });
  const showAlertBar = computed(() => {
    if (!formData.rejection) {
      return false;
    }
    return formData.status === 2 && formData.rejection != null;
  });
  const previewOnlineRef = ref<InstanceType<typeof PreviewOnline>>();
  const isSignsUpload = computed(() => route.query.status === '2');

  const previewOnline = (url: string | undefined, type) => {
    if (url) {
      previewOnlineRef.value?.open(url, type);
    }
  };
  const back = () => {
    router.push({
      name: 'responsibilityNoticeManage',
    });
  };
  const handleSubmit = () => {
    let signsUpload: any[] = [];
    let feedback: any[] = [];

    formRef.value?.validate(async (valid) => {
      if (valid) {
        submiting.value = true;
        if (isSignsUpload.value) {
          signsUpload = await formatAttachmentList(formData.signsUpload);
        } else {
          feedback = await formatAttachmentList(formData.feedback);
        }
        const params = {
          id: route.query.id,
          updateType: isSignsUpload.value ? 0 : 1,
          signsUpload: isSignsUpload.value ? JSON.stringify(signsUpload) : undefined,
          feedback: !isSignsUpload.value ? JSON.stringify(feedback) : undefined,
        };
        safetyNoticeDeptFeedback(params)
          .then(() => {
            router.push({
              name: 'responsibilityNoticeManage',
            });
          })
          .finally(() => {
            submiting.value = false;
          });
      }
    });
  };

  const handleUploadSignsUploadSuccess = (fileList) => {
    formData.signsUpload = fileList;
    formRef.value.validateField('signsUpload');
  };

  const handleUploadFeedbackUploadSuccess = (fileList) => {
    formData.feedback = fileList;
    formRef.value.validateField('feedback');
  };

  const handleQueryDetail = () => {
    safetyNoticeDeptQueryDetail({
      id: route.query.id,
    }).then((res) => {
      Object.keys(formData).forEach((name) => {
        if (name in res) {
          Object.assign(formData, {
            [name]: res[name],
            status: res.status,
            attachment: unformatAttachment(res.attachment),
            signsUpload: unformatAttachment(res.signsUpload),
            feedback: unformatAttachment(res.feedback),
            content: res.content,
          });
        }
      });
      console.log(formData);
    });
  };

  onMounted(() => {
    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;
  }

  .hint {
    margin-bottom: 10px;
    padding: 10px;
    background-color: rgb(255, 241, 241);
    color: rgb(255, 87, 87);
    border: 1px solid rgb(255, 87, 87);
    border-radius: 4px;
  }

  .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);
    }
  }
  .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);
  }
</style>
