<template>
  <div class="page-wrapper">
    <breadcrumb v-if="!multiPage" :breadcrumb-data="breadcrumbData" />
    <!-- 点检说明 -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      :rules="rules"
      :wrapper-col="{ span: 24 }"
    >
      <a-collapse
        default-active-key="a"
        expand-icon-position="right"
        class="collapse-header-divide"
      >
        <a-collapse-panel key="a" :header="$t('CHECK_DESC')">
          <!-- 点检说明table -->
          <MomTable
            ref="MomTable"
            row-key="id"
            :columns="tableColumns"
            :data-source="dataSource"
            :mega-extend="{
              rowAction: false,
            }"
            :pagination="false"
            :show-util-operator="false"
            class="pb-4"
          >
            <div slot="pcResult" slot-scope="text, record">
              <span class="status-box" :class="text">{{
                formatDataValue(resultList, record.pcResult)
              }}</span>
            </div>
            <div slot="standardValue" slot-scope="text, record">
              <span>{{ formatData(record) }}</span>
            </div>
            <div slot="audioUrl" slot-scope="text">
              <AudioCard v-if="text" :audio-url="text"></AudioCard>
            </div>
            <div slot="pcUrl" slot-scope="text, record">
              <img
                v-if="record.pcUrl"
                class="cursor-pointer"
                style="height: 24px"
                :src="`${systemConfig.FILE_SERVER}${record.pcUrl}`"
                @click="handlePreviewImg(record.pcUrl)"
              />
            </div>
          </MomTable>
        </a-collapse-panel>
      </a-collapse>
      <!-- 事件关注信息 开始 -->
      <EventFocusInfo v-if="detailInfo.eventCode" :detail-info="detailInfo" />
      <!-- 事件关注信息 结束 -->
      <!-- 位置信息 开始 -->
      <LocationInfo v-if="detailInfo.eventCode" :detail-info="detailInfo" />
      <!-- 位置信息 结束 -->
      <!-- 异常事件信息 开始 -->
      <EventInfo v-if="detailInfo.eventCode" :detail-info="detailInfo" />
      <!-- 异常事件信息 结束 -->
      <!-- 异常事件信息 开始 -->
      <EventTransferInfo
        v-if="detailInfo.transferList && detailInfo.transferList.length"
        :transfer-list="detailInfo.transferList"
      />
      <!-- 异常事件信息 结束 -->
      <!-- 异常事件历史 开始 -->
      <EventProcess :log-list="detailInfo.logList" :step-list="statusList" />
      <!-- 改进说明 -->
      <a-collapse
        default-active-key="b"
        expand-icon-position="right"
        class="collapse-header-divide improve-desc"
      >
        <a-collapse-panel key="b" :header="$t('IMPROVE_DESC')">
          <!-- 改进说明富文本 :label="$t('IMPROVE_DESC')" -->
          <a-form-model-item prop="improveRemark">
            <a-input
              v-model="form.improveRemark"
              type="textarea"
              allow-clear
              :max-length="500"
            />
          </a-form-model-item>
          <!-- :label="$t('LABEL_FILE')" list-type="picture-card" -->
          <a-form-model-item>
            <div class="upload-info upload-pdf">
              {{
                `*${$t("UPLOAD_FILE_CANNOT_EXCEED") + 25}MB! ${$t(
                  "UPLOAD_ONLY"
                )}pdf${$t("FILE")}`
              }}
            </div>
            <a-upload
              ref="aUpload"
              key="upload1"
              :action="url"
              accept=".pdf"
              :limit="1"
              :before-upload="beforeUpload"
              :default-file-list="fileList"
              :file-list="fileList"
              :multiple="true"
              :remove="handleRemove"
              @change="uploadSuccess"
            >
              <div>
                <a-button :disabled="fileList.length === 1">
                  <i
                    v-if="!loading"
                    slot="default"
                    class="iconfont icon-ge_shangchuan"
                    style="font-size: 18px; color: #0ea8d0"
                  ></i>
                  <a-icon v-else type="loading" />
                  <span>{{ $t("UPLOAD") }}</span>
                </a-button>
              </div>
            </a-upload>
          </a-form-model-item>
          <!-- :label="$t('CORE_PICTURE')" -->
          <a-form-model-item prop="improveImgUrlList">
            <!-- 多图片上传 -->
            <MultipleUpload
              v-model="form.improveImgUrlList"
              :image-url-list="improveImgUrlList"
              :limit="limit"
            />
            <div class="upload-info">
              {{ `*${$t("CORE_PICTURE") + $t("SIZE_LIMIT") + 5}MB!` }}
            </div>
          </a-form-model-item>
        </a-collapse-panel>
      </a-collapse>
    </a-form-model>
    <div class="page-bottom-op">
      <a-button type="primary" @click="confirm">
        <i class="iconfont icon-baocun"></i>
        {{ $t("SAVE") }}
      </a-button>
      <a-button @click="cancel">
        <i class="iconfont icon-quxiao"></i>
        {{ $t("BACK") }}
      </a-button>
    </div>
    <ImgViewer ref="megeIMg" :img-option="imgOption" :imgs="img">
      <img :imgs="img" />
    </ImgViewer>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { ImgViewer } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";
import FieldExtendMixin from "@/mixins/fieldExtend";
import { fetchFileUrl } from "@/utils/file";
import breadcrumb from "@/components/breadcrumb";
import MultipleUpload from "@/components/uploadPicture/multipleUpload";
import AudioCard from "@/components/AudioCard";
import EventInfo from "@/components/epms/EventDetail/EventInfo";
import LocationInfo from "@/components/epms/EventDetail/LocationInfo";
import EventFocusInfo from "@/components/epms/EventDetail/EventFocusInfo";
import EventProcess from "@/components/epms/EventDetail/EventProcess";
import EventTransferInfo from "@/components/epms/EventDetail/EventTransferInfo";

export default {
  components: {
    breadcrumb,
    AudioCard,
    MultipleUpload,
    ImgViewer,
    EventInfo,
    LocationInfo,
    EventFocusInfo,
    EventProcess,
    EventTransferInfo,
  },
  mixins: [FieldExtendMixin],
  data() {
    return {
      loading: false,
      limit: 5,
      breadcrumbData: [
        {
          name: this.$t("CHECK_REPORT"),
          url: "/eam/eqp_check/check_report",
        },
        { name: this.$t("ADD"), url: "" },
      ],
      dataSource: [],
      fileUrl: `${ApiConstant.PREFIX_CORE}/api/sys/file`,
      url: `${ApiConstant.PREFIX_CORE}/api/sys/file/upload`,
      headers: {
        Authorization: this.$auth.getToken("local"),
      },
      form: {
        resultId: "",
        improveRemark: "",
        improveImgUrlList: "",
        improveFileUrlList: "",
      },
      resultList: [],
      fileList: [],
      formOld: {
        resultId: "",
        improveRemark: "",
        improveImgUrlList: "",
        improveFileUrlList: "",
      },
      isClear: false,
      img: "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=85690711,3884201894&fm=27&gp=0.jpg",
      imgOption: {
        button: false,
        navbar: 0,
        title: false,
        toolbar: 0,
        isImgViewer: false,
      },
      improveImgUrlList: [],
      detailInfo: {},
      detailData: {},
      yesNoList: [],
      statusList: [],
    };
  },
  computed: {
    ...mapState("setting", ["multiPage"]),
    ...mapState({
      systemConfig: (state) => state.app.systemConfig,
    }),
    rules() {
      return {
        itemCode: [
          {
            required: true,
            max: 50,
            message: this.$t("PLACEENTER") + 50 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
      };
    },
    tableColumns() {
      return this.$observable("tableColumns", [
        {
          dataIndex: "itemName", // 点检项目
          title: () => `${this.$t("CHECK_CONTENT")}`,
          ellipsis: true,
          sorter: false,
          width: 260,
        },
        {
          dataIndex: "standardValue", // 标准值
          title: () => `${this.$t("STANDARD_VALUE")}`,
          ellipsis: true,
          sorter: false,
          width: 260,
          scopedSlots: { customRender: "standardValue" },
        },
        {
          dataIndex: "pcResult", // 点检结果
          title: () => `${this.$t("CHECK_RESULT")}`,
          ellipsis: true,
          sorter: false,
          width: 260,
          scopedSlots: { customRender: "pcResult" },
        },
        {
          dataIndex: "audioUrl", // 语音
          title: () => `${this.$t("VOICE")}`,
          ellipsis: true,
          sorter: false,
          width: 290,
          minWidth: 290,
          scopedSlots: { customRender: "audioUrl" },
        },
        {
          dataIndex: "pcUrl", // 点检图片
          title: () => `${this.$t("CHECK_IMAGE")}`,
          ellipsis: true,
          sorter: false,
          width: 300,
          scopedSlots: { customRender: "pcUrl" },
        },
        {
          dataIndex: "pcRemark", // 备注
          title: () => `${this.$t("REMARK")}`,
          ellipsis: true,
          sorter: false,
        },
        {
          dataIndex: "responsibleName", // 点检人员
          title: () => `${this.$t("CHECK_STAFF")}`,
          ellipsis: true,
          sorter: false,
          width: 300,
        },
      ]);
    },
    fileListArr() {
      return this.fileList;
    },
  },
  mounted() {
    const { id, resultId } = this.$route.query;
    if (id) {
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/epm/pcm/pc-task-rpt/detail?id=${id}`
        )
        .then((res) => {
          const {
            estEventId,
            improveFileUrlList,
            improveImgUrlList,
            improveRemark,
            resultItemList,
          } = res.data.data;
          this.fileList = improveFileUrlList?.length
            ? improveFileUrlList
                .filter((list) => list)
                .map((item) => {
                  const obj = {};
                  obj.url = fetchFileUrl(item, this);
                  obj.fileUrl = item;
                  obj.name = item;
                  obj.status = "done";
                  obj.type = "application/pdf";
                  obj.uid = item;
                  return obj;
                })
            : [];
          this.improveImgUrlList = improveImgUrlList
            ? [...improveImgUrlList]
            : [];
          this.form = {
            estEventId,
            resultId,
            improveFileUrlList: improveFileUrlList?.join(",") || "",
            improveImgUrlList: improveImgUrlList?.join(",") || "",
            improveRemark,
          };
          this.dataSource = resultItemList;
          this.formOld = {
            ...this.form,
            ...this.formOld,
          };
          this.getEstEventInfo();
        });
    }
    this.init();
  },
  methods: {
    init() {
      return Promise.all([
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:PC_RESULT`
        ), // 点检结果
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:COMMON:WHETHER_CHAR`
        ), // 是否
      ]).then(([resultRes, yesNoRes]) => {
        this.resultList = resultRes.data.data;
        this.yesNoList = yesNoRes.data.data;
      });
    },
    getEstEventInfo() {
      const { estEventId } = this.form;
      if (estEventId) {
        this.$axios
          .get(`${ApiConstant.PREFIX_CORE}/api/est/event/detail`, {
            params: {
              eventId: estEventId,
            },
          })
          .then((detailRes) => {
            this.detailInfo = detailRes.data.data;
            this.onGetProcessDetail();
          });
      }
    },
    // 获取流程详情
    onGetProcessDetail() {
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/est/process/get-by-id/${this.detailInfo.processId}`
        )
        .then((res) => {
          this.detailData = res.data?.data;
          this.statusList = res.data.data.stepList;
        });
    },
    // 预览图片
    handlePreviewImg(imgSrc) {
      if (!imgSrc) return;
      this.img = this.systemConfig.FILE_SERVER + imgSrc;
      this.$refs.megeIMg.showImg();
    },
    formatDataValue(data, status) {
      const result = data.find((item) => item.value === status.toString());
      return result ? result.label : "";
    },
    // 获取点检标准值
    formatData(row) {
      let value = "——";
      if (row.checkStyle === "TEXT") {
        value = row.textValue;
      } else if (row.checkStyle === "NUMBER") {
        const { compareType, upperLimit, lowerLimit } = row;
        switch (compareType) {
          case "=":
            value = `${this.$t("CHECK_RESULT")}=${upperLimit}=${lowerLimit}`;
            break;
          case "<":
            value = `${this.$t("CHECK_RESULT")}<${upperLimit}`;
            break;
          case ">":
            value = `${this.$t("CHECK_RESULT")}>${lowerLimit}`;
            break;
          case "<=>=":
            value = `${lowerLimit}<=${this.$t("CHECK_RESULT")}=<${upperLimit}`;
            break;
          case "<=>":
            value = `${lowerLimit}<=${this.$t("CHECK_RESULT")}<${upperLimit}`;
            break;
          case "<>=":
            value = `${lowerLimit}<${this.$t("CHECK_RESULT")}=<${upperLimit}`;
            break;
          case "<>":
            value = `${lowerLimit}<${this.$t("CHECK_RESULT")}<${upperLimit}`;
            break;
          default:
            value = `${this.$t("CHECK_RESULT")}=${upperLimit}=${lowerLimit}`;
            break;
        }
      }
      return value;
    },
    // 文件上传
    uploadSuccess(info) {
      this.fileList = info.fileList;
      if (info.file.status === "uploading") {
        // this.loading = true;
      }
      if (info.file.status === "done") {
        // Get this url from response in real world.
        // this.loading = false;
        const list = [];
        info.fileList.forEach((item) => {
          const data = {
            url: item.url ? item.url : item?.response?.data?.fileUrl,
            fileUrl: item.fileUrl
              ? item.fileUrl
              : item?.response?.data?.fileUrl,
          };
          list.push(data);
        });
        this.form.improveFileUrlList = list
          .map((item) => item.fileUrl)
          .join(",");
      }
    },
    handleRemove(file) {
      const list = this.fileList.filter(
        (item) => item.fileUrl !== file.fileUrl
      );
      this.form.improveFileUrlList = list.map((item) => item.fileUrl).join(",");
    },
    // 上传文件之前校验
    beforeUpload(file) {
      return new Promise((resolve, reject) => {
        if (file && file.name) {
          const fileSuffix = file.name.substr(file.name.lastIndexOf(".")); // 获取文件后缀名
          if (["pdf"].includes(fileSuffix)) {
            this.$message.warning(
              `${this.$t("UPLOAD_ONLY")}pdf${this.$t("FILE")}`
            );
            reject(file);
          }
        }
        const isLt2M = file.size / 1024 / 1024 < 25; // 判断文件大小是否小于25M
        if (!isLt2M) {
          this.$message.error(
            `${this.$t("UPLOAD_FILE_CANNOT_EXCEED") + 25}MB!`
          );
          reject(file);
        }
        resolve(file);
      });
    },
    cancel() {
      this.$store.dispatch("tagsView/jumpBeforeView", {
        to: { path: "/eam/eqp_check/check_report" },
        vm: this,
      });
    },
    confirm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const {
            resultId,
            improveFileUrlList,
            improveImgUrlList,
            improveRemark,
          } = this.form;
          const fileList =
            (improveFileUrlList && improveFileUrlList.split(",")) || [];
          const imgList =
            (improveImgUrlList && improveImgUrlList.split(",")) || [];
          const req = {
            resultId,
            improveFileUrlList: fileList,
            improveImgUrlList: imgList,
            improveRemark,
          };
          this.$axios
            .put(
              `${ApiConstant.PREFIX_CORE}/api/epm/pcm/pc-task-rpt/update`,
              req
            )
            .then(() => {
              this.$message.success(this.$t("EDIT_SUCCESS"));
              this.$store.dispatch("tagsView/jumpBeforeView", {
                to: { path: "/eam/eqp_check/check_report" },
                vm: this,
              });
            });
        }
      });
    },
  },
};
</script>
<style lang="less" scoped>
@import "@/assets/css/status_epms.less";
.collapse-header-divide.improve-desc {
  padding-bottom: 2.5rem;
  .upload-info.upload-pdf {
    position: absolute;
    top: 0.8rem;
    left: 5rem;
    width: 400px;
  }
  .upload-info {
    margin-top: -1.5rem;
    font-size: 14px;
    color: #c0c4cc;
  }
}
</style>
