<template>
  <div class="page-wrapper">
    <breadcrumb v-if="!multiPage" :breadcrumb-data="breadcrumbData" />
    <div class="page-container">
      <a-collapse
        v-model="activeKey"
        expand-icon-position="right"
        class="collapse-header-divide"
      >
        <a-collapse-panel key="a" :header="$t('BASE_INFO')">
          <a-descriptions>
            <!--点检对象编码-->
            <a-descriptions-item :label="`${$t('CHECK_OBJECT_CODE')}`">{{
              pcData.pcObjectCode || "--"
            }}</a-descriptions-item>
            <!--点检对象名称-->
            <a-descriptions-item :label="`${$t('CHECK_OBJECT_NAME')}`">{{
              pcData.pcObjectName || "--"
            }}</a-descriptions-item>
            <!--点检表单编码-->
            <a-descriptions-item :label="`${$t('CHECK_FORM_CODE')}`">{{
              pcData.pcFrmExtBPO.pcFrmCode || "--"
            }}</a-descriptions-item>
            <!--点检表单名称-->
            <a-descriptions-item :label="`${$t('CHECK_FORM_NAME')}`">{{
              pcData.pcFrmExtBPO.pcFrmName || "--"
            }}</a-descriptions-item>
            <!--点检分类-->
            <a-descriptions-item :label="`${$t('CHECK_TYPE')}`">{{
              pcData.pcFrmExtBPO.pcCategoryName || "--"
            }}</a-descriptions-item>
          </a-descriptions>
          <a-row v-if="pcData.pcFrmExtBPO.hasOwnProperty('opUrl')" :gutter="24">
            <a-col :span="8">
              <a-form-model-item :label="$t('CHECK_SOP')" prop="opUrl">
                <SingleUploadFile
                  v-model="pcData.pcFrmExtBPO.opUrl"
                  :disabled="true"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-collapse-panel>
      </a-collapse>
      <a-collapse
        v-model="activeKeyB"
        expand-icon-position="right"
        class="collapse-header-divide"
      >
        <a-collapse-panel key="b" :header="$t('CHECK_SOP')">
          <MomTable
            ref="MomTable"
            row-key="itemName"
            :action-buttons="actionButtons"
            :columns="columns"
            :data-source="pcFrmItemList"
            :pagination="false"
            :show-util-operator="false"
            @edit="handleEdit"
          >
            <a-row slot="toolbar" class="button-top-table">
              <a-button @click="handleAdd">
                <a-icon type="plus" /> {{ $t("ADD") }}
              </a-button>
            </a-row>
            <div slot="itemType" slot-scope="text, record">
              <span>{{ getAttrValue(itemTypeList, record.itemType) }}</span>
            </div>
            <div slot="imgFlag" slot-scope="text, record">
              <span>{{ getAttrValue(yesNoList, record.imgFlag) }}</span>
            </div>
            <div slot="pcResult" slot-scope="text, record">
              <span>{{ getAttrValue(pcResultList, record.pcResult) }}</span>
            </div>
            <div slot="checkStyle" slot-scope="text, record">
              <span>{{ getAttrValue(checkStyleList, record.checkStyle) }}</span>
            </div>
          </MomTable>
        </a-collapse-panel>
      </a-collapse>
    </div>
    <div class="page-bottom-op">
      <a-button @click="handleCancel">
        <i class="iconfont icon-quxiao"></i>
        {{ $t("BACK") }}
      </a-button>
    </div>
    <MegaDrawer
      width="520"
      :title="
        isEdit
          ? $t('EQP_CHECK_METHOD') + $t('EDIT')
          : $t('EQP_CHECK_METHOD') + $t('ADD')
      "
      :visible="drawerVisible"
      :confirm-loading="confirmLoading"
      @close="handleCloseDrawer"
      @cancel="handleCloseDrawer"
      @ok="handleSaveDrawer"
    >
      <a-form-model
        slot="main"
        ref="ruleFormDrawer"
        layout="vertical"
        :model="drawerForm"
        :rules="rulesDrawer"
      >
        <a-form-model-item
          :label="`${$t('CHECK_CONTENT')}${$t('NAME')}`"
          prop="itemName"
        >
          <a-input
            v-model="drawerForm.itemName"
            :placeholder="$t('PLACEENTER')"
            :disabled="!drawerForm.id || !drawerForm.id.includes('A')"
            @change="
              drawerForm.itemName = drawerForm.itemName.slice(0, 50).trim()
            "
          />
        </a-form-model-item>
        <a-form-model-item
          v-if="drawerForm.checkStyle != 'NUMBER'"
          :label="$t('CHECK_RESULT')"
          prop="pcResult"
        >
          <a-radio-group v-model="drawerForm.pcResult">
            <a-radio
              v-for="okItem in okNgList"
              :key="okItem.value"
              :value="okItem.value"
              >{{ okItem.label }}</a-radio
            >
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item
          v-if="drawerForm.checkStyle === 'NUMBER'"
          :label="$t('CHECK_RESULT')"
          prop="pcValue"
        >
          <a-input-number
            v-model="drawerForm.pcValue"
            class="relative"
            style="width: 100%"
            :placeholder="$t('PLACEENTER')"
          />
        </a-form-model-item>
        <a-form-model-item
          v-if="drawerForm.checkStyle === 'TEXT'"
          :label="$t('CHECK_RESULT')"
          prop="pcValue"
        >
          <a-input
            v-model="drawerForm.pcValue"
            :placeholder="$t('PLACEENTER')"
            @change="
              drawerForm.pcValue = drawerForm.pcValue.slice(0, 255).trim()
            "
          />
        </a-form-model-item>
        <a-form-model-item
          v-if="drawerForm.imgFlag === 'Y'"
          :label="`${$t('IMPORT')}${$t('OPERATION')}${$t('CORE_PICTURE')}`"
          allow-clear
          prop="pcUrl"
        >
          <SingleUpload
            v-model="drawerForm.pcUrl"
            :disabled="true"
            :is-show-button="isShowButton"
          />
        </a-form-model-item>
        <a-form-model-item :label="$t('REMARK')" prop="remark">
          <a-input
            v-model="drawerForm.remark"
            :placeholder="$t('PLACEENTER')"
            onkeyup="value=value.slice(0, 50)"
          />
        </a-form-model-item>
      </a-form-model>
    </MegaDrawer>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { uniqBy } from "lodash";
import { Drawer as MegaDrawer } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";
import { fieldExReqDataFn } from "@/utils/fieldExtend";
import FieldExtendMixin from "@/mixins/fieldExtend";
import breadcrumb from "@/components/breadcrumb";

import SingleUpload from "@/components/uploadPicture/singleUpload";
import SingleUploadFile from "@/components/uploadFile/singleUpload";

export default {
  components: {
    breadcrumb,
    MegaDrawer,
    SingleUpload,
    SingleUploadFile,
  },
  mixins: [FieldExtendMixin],
  data() {
    return {
      breadcrumbData: [
        {
          name: this.$t("CHECK_FORM"),
          url: "/eam/eqp_check/check_form",
        },
        { name: this.$t("CHECK_FORM_EDIT"), url: "" },
      ],
      tableNameList: [
        {
          key: "epm_pc_frm",
          tab: "点检表单",
        },
      ],
      activeKey: "a",
      activeKeyB: "b",
      isShowButton: false,
      confirmLoading: false,
      dataSource: [],
      pcResultList: [],
      addNum: 0,
      pcData: {
        id: "",
        pcObjectCode: "",
        pcObjectName: "",
        pcFrmExtBPO: {
          pcFrmCode: "",
          pcFrmName: "", // 点检表单名称
          pcCategoryId: "", // 点检分类
          opUrl: "", // 图片或视频地址
        },
      },
      pcFrmItemList: [],
      drawerForm: {
        itemName: "", // 	点检项名称
        itemType: "", // 点检项类型
        checkStyle: "", // 点检方式
        compareType: "", // 比较方式
        lowerLimit: "", // 标准下限
        textValue: "", // 文本标准值
        autoMatchKey: "", // 自动匹配的Key
        opDescription: "", // 操作说明
        opUrl: "", // 操作说明地址：图片或视频
        imgFlag: "Y", // 是否上传点检图片
        noShowLow: true,
        noShowUp: true,
        fieldExtendList: [],
      },
      checkStyleList: [], // 点检方式列表
      itemTypeList: [], // 项目类型列表
      compareTypeList: [], // 点检项比较方式列表
      yesNoList: [], // 是否列表
      okNgList: [
        { label: "OK", value: "Y" },
        { label: "NG", value: "N" },
      ],
      fieldExtendList: [], // 字段扩展列表
      dynamicFieldList: [], // 字段扩展列表动态
      drawerVisible: false,
      isEdit: false,
      editIndex: 0,
      actionButtons: [
        "edit",
        (h, { record, index }) =>
          record.id.includes("A") && (
            <a-button
              type="link"
              onClick={() => this.handleDelete(record, index)}
            >
              <i
                class="operation-icon iconfont icon-delete"
                style="font-size:18px;color:#d45f5f"
                title={this.$t("DELETE")}
              />
            </a-button>
          ),
      ],
      defaultList: [
        {
          dataIndex: "itemName", // 点检项名称
          sorter: false,
          ellipsis: true,
          title: () => this.$t("CHECK_CONTENT"),
        },
        {
          dataIndex: "pcCategoryName", // 点检分类
          title: () => `${this.$t("CHECK_TYPE")}${this.$t("NAME")}`,
          ellipsis: true,
          sorter: false,
        },
        {
          dataIndex: "pcResult", // 点检结果
          sorter: false,
          ellipsis: true,
          title: () => this.$t("CHECK_RESULT"),
          scopedSlots: { customRender: "pcResult" },
        },
        {
          dataIndex: "imgFlag",
          align: "left",
          sorter: false,
          ellipsis: true,
          title: () => this.$t("IMG_FLAG"), // 是否上传图片
          scopedSlots: { customRender: "imgFlag" },
        },
        {
          dataIndex: "checkStyle", // 点检方式
          sorter: false,
          ellipsis: true,
          title: () => this.$t("EQP_CHECK_METHOD"),
          scopedSlots: { customRender: "checkStyle" },
        },
        {
          dataIndex: "itemType", // 点检项类型
          sorter: false,
          ellipsis: true,
          title: () => this.$t("PROJECT_TYPE"),
          scopedSlots: { customRender: "itemType" },
        },
        {
          dataIndex: "compareType", // 点检项类型
          sorter: false,
          ellipsis: true,
          title: () => this.$t("COMPARISON_MODE"),
          scopedSlots: { customRender: "compareType" },
        },
        {
          dataIndex: "upperLimit", // 点检项类型
          sorter: false,
          ellipsis: true,
          title: () => this.$t("STANDARD_UPPER_LIMIT"),
        },
        {
          dataIndex: "lowerLimit", // 点检项类型
          sorter: false,
          ellipsis: true,
          title: () => this.$t("STANDARD_LOWER_LIMIT"),
        },
        {
          dataIndex: "autoMatchKey", // 点检项类型
          sorter: false,
          ellipsis: true,
          title: () => this.$t("AUTO_MATCH_KEY"),
        },
        {
          dataIndex: "textValue", // 点检项类型
          sorter: false,
          ellipsis: true,
          title: () => this.$t("STANDARD_VALUE"),
        },
        {
          dataIndex: "opDescription", // 操作说明
          sorter: false,
          ellipsis: true,
          title: () => this.$t("OPERATING_INSTRUCTION"),
        },
      ],
      columnsItem: {
        dataIndex: "",
        title: "",
        ellipsis: true,
        sorter: false,
      },
      selectedRowKeys: [], // 选中行 key 数据
      selectedRows: [], // 选中行 数据
      columnsList: [],
    };
  },
  computed: {
    ...mapState("setting", ["multiPage"]),
    rules() {
      return {
        pcFrmCode: [
          {
            required: true,
            max: 50,
            message: () => this.$t("PLACEENTER") + 50 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        pcFrmName: [
          {
            required: true,
            max: 50,
            message: () => this.$t("PLACEENTER") + 50 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
      };
    },
    rulesDrawer() {
      return {
        itemName: [
          {
            required: true,
            max: 50,
            message: () => this.$t("PLACEENTER") + 50 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        imgFlag: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        pcValue: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "blur",
          },
        ],
        pcResult: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "blur",
          },
        ],
      };
    },
    columns() {
      return [...this.defaultList, ...this.columnsList];
    },
  },
  watch: {},
  mounted() {
    // 初始化数据
    this.init();
  },
  methods: {
    // 初始化数据
    init() {
      const params =
        this.$route.query.from === "maintain"
          ? {
              pmTaskId: this.$route.query.id,
            }
          : {
              id: this.$route.query.id,
              updateFlag: "Y",
            };
      const url =
        this.$route.query.from === "maintain"
          ? "/api/epm/pcm/pc-task/get-detail-by-pm-task-id"
          : "/api/epm/pcm/pc-task/get-detail-by-id";
      return Promise.all([
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:PC_CHECK_STYLE`
        ), // 点检方式
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:PC_ITEM_TYPE`
        ), // 点检项类型
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:PC_COMPARE_TYPE`
        ), // 点检项比较方式
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:COMMON:WHETHER_CHAR`
        ), // 是否
        this.$axios.get(`${ApiConstant.PREFIX_CORE}${url}`, {
          params: { ...params },
        }), // 点检对象来源配置详情
        // 点检结果
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:PC_RESULT`
        ),
      ]).then(
        ([
          checkStyleRes,
          itemTypeRes,
          compareTypeRes,
          yesNoRes,
          detailRes,
          pcResultRes,
        ]) => {
          this.checkStyleList = checkStyleRes.data.data;
          this.itemTypeList = itemTypeRes.data.data;
          this.compareTypeList = compareTypeRes.data.data;
          this.yesNoList = yesNoRes.data.data;
          /* eslint-enable */
          this.pcData = { ...detailRes.data?.data };
          const list = detailRes.data?.data?.pcFrmExtBPO?.pcFrmItemList || [];
          this.pcFrmItemList = [...list];
          this.pcResultList = pcResultRes.data.data || [];
        }
      );
    },
    // 监听新增点击事件
    handleAdd() {
      this.addNum += 1;
      this.drawerForm = {
        id: `A${this.addNum}`,
        itemName: "", // 	点检项名称
        itemType: "", // 点检项类型
        checkStyle: "", // 点检方式
        compareType: "", // 比较方式
        lowerLimit: "", // 标准下限
        textValue: "", // 文本标准值
        autoMatchKey: "", // 自动匹配的Key
        opDescription: "", // 操作说明
        opUrl: "", // 操作说明地址：图片或视频
        imgFlag: "N", // 是否上传点检图片
        noShowLow: true,
        noShowUp: true,
        fieldExtendList: [],
      };
      this.drawerForm.fieldExtendList = this.fieldExtendList;
      this.isEdit = false;
      this.drawerVisible = true;
    },
    handleEdit(row) {
      const index = this.pcFrmItemList.findIndex((item) => item.id === row.id);
      this.editIndex = index;
      this.isEdit = true;
      this.drawerForm = { ...row };
      this.drawerVisible = true;
    },
    handleDelete(row) {
      const index = this.pcFrmItemList.findIndex((item) => item.id === row.id);
      this.$confirm({
        title: this.$t("DELETE"),
        content: this.$t("DELETE_INFO"),
        okText: this.$t("DELETE"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "close-circle",
        onOk: () => {
          this.pcFrmItemList.splice(index, 1);
        },
      });
    },
    pcResultJudge(cData, data) {
      let result = "ERROR";
      switch (data.compareType) {
        case "=":
          if (cData === data.upperLimit && cData === data.lowerLimit) {
            result = "NORMAL";
          }
          break;
        case "<":
          if (cData < data.upperLimit) {
            result = "NORMAL";
          }
          break;
        case ">":
          if (cData > data.lowerLimit) {
            result = "NORMAL";
          }
          break;
        case "<=>=":
          if (cData >= data.lowerLimit && cData <= data.upperLimit) {
            result = "NORMAL";
          }
          break;
        case "<=>":
          if (cData > data.lowerLimit && cData <= data.upperLimit) {
            result = "NORMAL";
          }
          break;
        case "<>=":
          if (cData >= data.lowerLimit && cData < data.upperLimit) {
            result = "NORMAL";
          }
          break;
        case "<>":
          if (cData > data.lowerLimit && cData < data.upperLimit) {
            result = "NORMAL";
          }
          break;
        default:
          break;
      }
      return result;
    },
    handleSaveDrawer() {
      this.$refs.ruleFormDrawer.validate((valid) => {
        if (valid) {
          if (this.drawerForm.checkStyle === "NUMBER") {
            this.drawerForm.pcResult = this.pcResultJudge(
              this.drawerForm.pcValue,
              this.drawerForm
            );
          } else {
            this.drawerForm.pcResult =
              this.drawerForm.pcResult === "OK" ? "NORMAL" : "ERROR";
          }
          this.handleCloseDrawer();
          if (!this.isEdit) {
            this.pcFrmItemList.push({ ...this.drawerForm });
          } else {
            this.pcFrmItemList[this.editIndex] = { ...this.drawerForm };
          }
          this.selectedRowKeys = [];
          this.selectedRows = [];
        }
      });
    },
    handleCloseDrawer() {
      this.confirmLoading = false;
      this.$refs.ruleFormDrawer.clearValidate();
      this.drawerVisible = false;
    },
    // 监听保存按钮点击事件
    handleSave() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          const sdata = {
            id:
              this.$route.query.from === "maintain" ? "" : this.$route.query.id,
            pcObjectCode: this.pcData.pcObjectCode,
            pcObjectId: this.pcData.pcObjectId,
            pcObjectName: this.pcData.pcObjectName,
            opUrl: this.pcData.pcFrmExtBPO.opUrl,
            newOpUrl: this.pcData.pcFrmExtBPO.newOpUrl,
            pcResultItemList: [...this.pcFrmItemList],
            pcType: this.$route.query.from === "maintain" ? "PM_PC" : "NORMAL",
            resultRemark: this.pcData.resultRemark,
            resultImgList: this.pcData.resultImgList
              ? this.pcData.resultImgList.split(",")
              : [],
          };
        }
      });
    },
    // 监听取消按钮点击事件
    handleCancel() {
      this.$store.dispatch("tagsView/jumpBeforeView", {
        to: {
          path: "/eam/eqp_check/check_task",
        },
        vm: this,
      });
    },
    // 页面埋点
    handleFuncUseRate(data) {
      this.$axios
        .put(`${ApiConstant.PREFIX_CORE}/api/epm/eam/use`, data)
        .then(() => {});
    },
  },
};
</script>
<style lang="less" scoped>
@import "@/assets/css/fault_repair.less";
/deep/ .mega-design-business-table .mega-design-pro-table {
  padding: 0 !important;
  margin-bottom: 24px;
}
/deep/ .ant-form-item-label {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>

<style lang="less">
.icon-bianji2 {
  color: @primary-color !important;
}
.status-btn {
  cursor: pointer;
  margin-top: 0;
  margin-left: 6px;
  min-width: 100px;
  height: 36px;
  background: #fff;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  text-align: center;
  line-height: 36px;
  position: relative;
  padding: 0 6px;
}
.statusActive {
  border: 1px solid #ff3250;
}
.icon-box {
  padding: 5px;
  position: absolute;
  right: -1px;
  bottom: -1px;
  border-radius: 4px;
  .icon-gougou {
    color: #fff;
    height: 4px;
    font-size: 12px;
  }
  .icon-gougou::before {
    position: relative;
    top: -16px;
  }
}
</style>
