<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('MAINTENANCE_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="pmUrl" slot-scope="text, record">
              <img
                v-if="record.pmUrl"
                class="cursor-pointer"
                style="height: 24px"
                :src="`${systemConfig.FILE_SERVER}${record.pmUrl}`"
                @click="handlePreviewImg(record.pmUrl)"
              />
            </div>
            <div slot="audioUrl" slot-scope="text">
              <AudioCard v-if="text" :audio-url="text"></AudioCard>
            </div>
          </MomTable>
        </a-collapse-panel>
      </a-collapse>
      <!-- 改进说明 -->
      <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>
          <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>
          <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-collapse
        default-active-key="c"
        expand-icon-position="right"
        class="collapse-header-divide improve-desc"
      >
        <a-collapse-panel key="c" :header="$t('LIFT_AFTER_MAINTENANCE')">
          <a-form-model-item prop="continueMonth">
            <a-input
              v-model.trim="form.continueMonth"
              type="number"
              oninput="value=value.replace(/\D|^0/g,'')"
              allow-clear
              :placeholder="$t('PLACEENTER')"
            />
          </a-form-model-item>
          <div style="color: #f00">
            {{ $t("LIFT_AFTER_MAINTENANCE_TIP") }}
          </div>
        </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";

export default {
  components: {
    MultipleUpload,
    breadcrumb,
    ImgViewer,
    AudioCard,
  },
  mixins: [FieldExtendMixin],
  data() {
    return {
      loading: false,
      limit: 5,
      breadcrumbData: [
        {
          name: this.$t("MAINTENANCE_REPORT"),
          url: "/eam/eqp_maintain/maintenance_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: {
        taskId: "",
        improveRemark: "",
        improveImgUrlList: "",
        improveFileUrlList: "",
        continueMonth: 0,
      },
      fileList: [],
      formOld: {
        taskId: "",
        improveRemark: "",
        improveImgUrlList: "",
        improveFileUrlList: "",
        continueMonth: 0,
      },
      improveImgUrlList: [],
      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,
      },
    };
  },
  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("MAINTENANCE_CONTENT")}`,
          ellipsis: true,
          sorter: false,
          width: 260,
        },
        {
          dataIndex: "opDescription", // 保养说明
          title: () => `${this.$t("MAINTENANCE_DESC")}`,
          ellipsis: true,
          sorter: false,
          width: 260,
        },
        {
          dataIndex: "audioUrl", // 语音
          title: () => `${this.$t("VOICE")}`,
          ellipsis: true,
          sorter: false,
          width: 290,
          minWidth: 290,
          scopedSlots: { customRender: "audioUrl" },
        },
        {
          dataIndex: "pmUrl", // 保养图片
          title: () => `${this.$t("MAINTENANCE_IMAGE")}`,
          ellipsis: true,
          sorter: false,
          width: 300,
          scopedSlots: { customRender: "pmUrl" },
        },
        {
          dataIndex: "pmRemark", // 备注
          title: () => `${this.$t("REMARK")}`,
          ellipsis: true,
          sorter: false,
        },
        {
          dataIndex: "responsibleName", // 保养人员
          title: () => `${this.$t("MAINTENANCE_STAFF")}`,
          ellipsis: true,
          sorter: false,
          width: 300,
        },
      ]);
    },
    fileListArr() {
      return this.fileList;
    },
  },
  mounted() {
    const { id } = this.$route.query;
    if (id) {
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/epm/pmm/pm-task-rpt/detail?id=${id}`
        )
        .then((res) => {
          const {
            improveFileUrlList,
            improveImgUrlList,
            improveRemark,
            continueMonth,
            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 = {
            taskId: id,
            improveFileUrlList: improveFileUrlList?.join(",") || "",
            improveImgUrlList: improveImgUrlList?.join(",") || "",
            improveRemark,
            continueMonth,
          };
          this.dataSource = resultItemList;
          this.formOld = {
            ...this.form,
            ...this.formOld,
          };
        });
    }
  },
  methods: {
    // 预览图片
    handlePreviewImg(imgSrc) {
      this.img = this.systemConfig.FILE_SERVER + imgSrc;
      this.$refs.megeIMg.showImg();
    },
    // 文件上传
    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_maintain/maintenance_report" },
        vm: this,
      });
    },
    confirm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const {
            taskId,
            improveFileUrlList,
            improveImgUrlList,
            improveRemark,
            continueMonth,
          } = this.form;
          const fileList =
            (improveFileUrlList && improveFileUrlList.split(",")) || [];
          const imgList =
            (improveImgUrlList && improveImgUrlList.split(",")) || [];
          const month = continueMonth ? parseInt(continueMonth, 10) : null;
          const req = {
            taskId,
            improveFileUrlList: fileList,
            improveImgUrlList: imgList,
            improveRemark,
            continueMonth: month,
          };
          this.$axios
            .put(
              `${ApiConstant.PREFIX_CORE}/api/epm/pmm/pm-task-rpt/update`,
              req
            )
            .then(() => {
              this.$message.success(this.$t("EDIT_SUCCESS"));
              this.$store.dispatch("tagsView/jumpBeforeView", {
                to: { path: "/eam/eqp_maintain/maintenance_report" },
                vm: this,
              });
            });
        }
      });
    },
  },
};
</script>
<style lang="less" scoped>
.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>
