<template>
  <view class="container">
    <view class="tips_text">
      严禁在本互联网非涉密平台处理、传输国家秘密和工作秘密，请确认扫描、传输的文件资料不涉及国家秘密和工作秘密
    </view>
    <u--form
      ref="formRef"
      label-position="left"
      :model="form"
      :rules="rules"
      label-width="auto"
    >

      <u-form-item
          label="隐患图片"
          prop="hiddenImgs"
          border-bottom
          required
          label-position="top"
      >
        <u-upload
            style="margin-top: 20upx"
            :file-list="form.hiddenImgs"
            multiple
            :max-count="max_count"
            :key = "uploadKey"
            @afterRead="fnHiddenImgsAfterRead"
            @delete="fnHiddenImgsDelete"
        />
      </u-form-item>

      <view class="ai_btn">
        <view class="ai_btn_con" @click="goIdentifyImg">
          <image src="../../static/png/ai_img.png" style="width: 16px;height: 16px"/>
          <view class="text" style="margin-left: 5px;"> AI隐患识别与处置</view>
        </view>
      </view>

      <u-form-item
        label="检查内容"
        prop="INSPECT_CONTENT"
        border-bottom
        required
        label-position="top"
      >
        <u--textarea
          v-model="form.INSPECT_CONTENT"
          disabled
          placeholder="请输入检查内容"
          border="none"
          auto-height
        />
      </u-form-item>
      <u-form-item
        label="隐患描述"
        prop="HIDDENDESCR"
        border-bottom
        required
        label-position="top"
      >
        <u--textarea
          v-model="form.HIDDENDESCR"
          placeholder="请输入隐患描述"
          border="none"
        />
      </u-form-item>
      <u-form-item
          v-show="aiFlag"
          label="法律依据"
          prop="LEGALBASIS"
          border-bottom
          required
          label-position="top"
      >
        <u--textarea
            v-model="form.LEGALBASIS"
            placeholder="请输入法律依据"
            border="none"
            disabled
            auto-height
        />
      </u-form-item>
      <u-form-item label="隐患部位" prop="HIDDENPART" border-bottom required>
        <u--input
          v-model="form.HIDDENPART"
          border="none"
          input-align="right"
          placeholder="请输入隐患部位"
        />
      </u-form-item>
      <u-form-item
        label="隐患级别"
        prop="HIDDENLEVEL_NAME"
        border-bottom
        required
        @click="fnHiddenLevelPickerShow"
      >
        <u--input
          :value="form.HIDDENLEVEL_NAME || '请选择'"
          readonly
          border="none"
          input-align="right"
        />
        <u-icon name="arrow-right" color="#999999"></u-icon>
      </u-form-item>
      <u-form-item label="整改意见" prop="DISPOSE" border-bottom required label-position="top">

        <u--textarea
            v-model="form.DISPOSE"
            placeholder="请输入整改意见"
            border="none"
            maxlength="200"
            auto-height
        />
      </u-form-item>
      <u-form-item
        label="发现时间"
        prop="DISCOVER_TIME"
        border-bottom
        required
        @click="fnDiscoverTimeShowChange"
      >
        <u--input
          :value="form.DISCOVER_TIME || '请选择'"
          readonly
          border="none"
          input-align="right"
        />
        <u-icon name="arrow-right" color="#999999"></u-icon>
      </u-form-item>
      <u-form-item
        label="整改截止时间"
        prop="RECTIFY_DEADLINE"
        border-bottom
        required
        @click="fnRectifyDeadlineShowChange"
      >
        <u--input
          :value="form.RECTIFY_DEADLINE || '请选择'"
          readonly
          border="none"
          input-align="right"
        />
        <u-icon name="arrow-right" color="#999999"></u-icon>
      </u-form-item>


      <u-button type="primary" text="保存" @click="fnSubmit" />
    </u--form>
    <u-picker
      :show="hiddenLevelPickerShow"
      :columns="hiddenLevelList"
      key-name="NAME"
      @cancel="fnHiddenLevelPickerShow"
      @confirm="fnHiddenLevelPickerConfirm"
    />
    <u-datetime-picker
      v-model="discoverTimeCurrent"
      :show="discoverTimeShow"
      mode="datetime"
      @cancel="fnDiscoverTimeShowChange"
      @confirm="fnInspectTimeConfirm"
    />
    <u-datetime-picker
      v-model="rectifyDeadlineCurrent"
      :show="rectifyDeadlineShow"
      mode="date"
      @cancel="fnRectifyDeadlineShowChange"
      @confirm="fnRectifyDeadlineConfirm"
    />
  </view>
</template>

<script>
import { getHiddenLevel,setSpecialRectificationInspectionHiddenAIImgAdd } from "@/api";
import debounce from "@/utils/debounce";
import store from "../../store";

export default {
  data() {
    return {
      type: "",
      deleteKey: false,
      index: 0,
      deleteImgsId: [],
      aiFlag: false,
      IDENTIFY_ID: '',
      max_count: 4,
      uploadKey: Math.random(),
      getUserInfo : store.getters.getUserInfo,
      form: {
        CONTENT_ID: "",
        IDENTIFY_ID: "",
        INSPECT_CONTENT: "",
        HIDDENDESCR: "",
        HIDDENPART: "",
        HIDDENLEVEL: "",
        HIDDENLEVEL_NAME: "",
        LEGALBASIS: "",
        DISPOSE: "",
        DISCOVER_TIME: "",
        RECTIFY_DEADLINE: "",
        hiddenImgs: [],
      },
      rules: {
        INSPECT_CONTENT: {
          type: "string",
          required: true,
          message: "请输入检查内容",
          trigger: ["blur", "change"],
        },
        HIDDENDESCR: {
          type: "string",
          required: true,
          message: "请输入隐患描述",
          trigger: ["blur", "change"],
        },
        HIDDENPART: {
          type: "string",
          required: true,
          message: "请输入隐患部位",
          trigger: ["blur", "change"],
        },
        HIDDENLEVEL_NAME: {
          type: "string",
          required: true,
          message: "请选择隐患级别",
          trigger: ["change"],
        },
        DISPOSE: {
          type: "string",
          required: true,
          message: "请输入整改意见",
          trigger: ["blur", "change"],
        },
        DISCOVER_TIME: {
          type: "string",
          required: true,
          message: "请选择发现时间",
          trigger: ["change"],
        },
        RECTIFY_DEADLINE: {
          type: "string",
          required: true,
          message: "请选择整改截止时间",
          trigger: ["change"],
        },
        hiddenImgs: {
          type: "array",
          required: true,
          message: "请上传隐患照片",
          trigger: ["change"],
        },
      },
      hiddenLevelPickerShow: false,
      hiddenLevelList: [],
      discoverTimeShow: false,
      discoverTimeCurrent: Number(new Date()),
      rectifyDeadlineShow: false,
      rectifyDeadlineCurrent: Number(new Date()),
    };
  },
  onLoad(query) {
    if (
      query.SPECIAL_RECTIFICATION_INSPECT_CONTENT_ID &&
      query.SPECIAL_RECTIFICATION_INSPECT_CONTENT_ID !== "undefined" &&
      query.SPECIAL_RECTIFICATION_INSPECT_CONTENT_ID !== "null"
    ) {
      this.form.SPECIAL_RECTIFICATION_INSPECT_CONTENT_ID =
        query.SPECIAL_RECTIFICATION_INSPECT_CONTENT_ID;
    }
    this.type = query.type;
    this.index = query.index;
    this.form.CONTENT_ID = query.CONTENT_ID;
    this.form.INSPECT_CONTENT = query.INSPECT_CONTENT;
    this.fnGetHiddenLevel();
    this.getOpenerEventChannel().on("hiddenEdit", (event) => {
      this.form.AI_FLAG = event.form.AI_FLAG
      if (query.type === "edit" && this.form.AI_FLAG === 1){
        this.aiFlag = true
      }
      this.form = event.form;
    });
    if (query.type === "edit"){
      this.deleteKey = true
      uni.setNavigationBarTitle({
        title: "修改隐患", // 设置页面标题为"新的标题"
      });
    }
  },
  methods: {
    async fnGetHiddenLevel() {
      const resData = await getHiddenLevel();
      this.hiddenLevelList.push(resData.list);
    },
    fnHiddenLevelPickerShow() {
      this.hiddenLevelPickerShow = !this.hiddenLevelPickerShow;
    },
    fnHiddenLevelPickerConfirm(event) {
      this.form.HIDDENLEVEL_NAME = event.value[0].NAME;
      this.form.HIDDENLEVEL = event.value[0].BIANMA;
      this.fnHiddenLevelPickerShow();
    },
    fnDiscoverTimeShowChange() {
      this.discoverTimeShow = !this.discoverTimeShow;
    },
    fnInspectTimeConfirm(event) {
      this.form.DISCOVER_TIME = uni.$u.timeFormat(
        event.value,
        "yyyy-mm-dd hh:MM",
      );
      this.fnDiscoverTimeShowChange();
    },
    fnRectifyDeadlineShowChange() {
      this.rectifyDeadlineShow = !this.rectifyDeadlineShow;
    },
    fnRectifyDeadlineConfirm(event) {
      this.form.RECTIFY_DEADLINE = uni.$u.timeFormat(event.value, "yyyy-mm-dd");
      this.fnRectifyDeadlineShowChange();
    },
    fnHiddenImgsAfterRead(event) {
      this.form.hiddenImgs.push(...event.file);
    },
    fnHiddenImgsDelete(event) {
      this.max_count = 4
      this.deleteKey = false
      this.uploadKey = Math.random()
      if (event.file.SPECIAL_RECTIFICATION_FILES_ID) {
        this.deleteImgsId.push(event.file.SPECIAL_RECTIFICATION_FILES_ID);
      }
      if (this.aiFlag) {
        this.clearIdentifyInfo()
      }
      this.form.hiddenImgs.splice(event.index, 1);
    },
    fnSubmit() {
      debounce(async () => {
        this.$refs.formRef
          .validate()
          .then(async () => {
            this.getOpenerEventChannel().emit("hiddenAdd", {
              form: { ...this.form, id: uni.$u.guid() ,AI_FLAG: this.aiFlag ? 1 : 0},
              SPECIAL_RECTIFICATION_FILES_ID: this.SPECIAL_RECTIFICATION_FILES_ID,
              type: this.type,
              index: this.index,
              deleteImgsId: this.deleteImgsId,
            });
            uni.$u.toast("保存成功");
            uni.navigateBack();
          })
          .catch(() => {
            uni.$u.toast("请填写完整信息");
          });
      });
    },
    async goIdentifyImg() {
      if (this.form.hiddenImgs.length === 0) {
        uni.showToast({
          icon: 'none',
          title: '请先上传图片',
          duration: 2000
        });
        return;
      } else if (this.form.hiddenImgs.length > 1) {
        uni.showToast({
          icon: 'none',
          title: '识别暂时只能上传一张图片',
          duration: 2000
        });
      } else {
        if(this.deleteKey){
          uni.showToast({
            icon: 'none',
            title: '请删除图片重新上传图片后,再次进行图片识别',
            duration: 2000
          });
          return;
        }
        var _this = this;
        uni.showLoading({
          title: '识别中...'
        })
        const files = [];
        files.push({
          uri: this.form.hiddenImgs[0].url,
          name: "imgsList",
        });
        let resData = await setSpecialRectificationInspectionHiddenAIImgAdd({
          loading: false,
          files,
          formData: {
            USER_ID: this.getUserInfo.USER_ID,
            DEPARTMENT_ID: this.getUserInfo.DEPARTMENT_ID,
          },
        });
        _this.aiFlag = true
        if ("success" == resData.result) {
          const aiHiddens = resData.aiHiddens;
          let hiddenDescr = ""
          let rectificationSuggestions = ""
          let legalBasis = ""
          aiHiddens.forEach((item) => {
            hiddenDescr += JSON.parse(item).hiddenDescr + ";"
            rectificationSuggestions += JSON.parse(item).rectificationSuggestions + ";"
            legalBasis += JSON.parse(item).legalBasis + ";"
          })
          _this.form.HIDDENLEVEL = 'hiddenLevel0001'
          _this.form.HIDDENLEVEL_NAME = '一般隐患'
          _this.form.IDENTIFY_ID = resData.IDENTIFY_ID
          _this.form.HIDDENDESCR = hiddenDescr
          _this.form.LEGALBASIS = legalBasis
          _this.form.DISPOSE = rectificationSuggestions
          _this.max_count = 1
          _this.uploadKey = Math.random()
        } else {
          uni.showModal({
            content: resData.exception,
            showCancel: false
          });
        }
        uni.hideLoading();
      }
    },
    clearIdentifyInfo() {
      this.aiFlag = false
      this.form.HIDDENLEVEL = ''
      this.form.HIDDENLEVEL_NAME = ''
      this.form.HIDDENDESCR = ""
      this.form.LEGALBASIS = ""
      this.form.DISPOSE = ""
      this.form.IDENTIFY_ID = ""
    }
  },
};
</script>

<style scoped lang="scss">
.container {
  padding: 20upx;
}

.ai_btn {
  width: 100%;
  box-sizing: border-box;
  background: #FFFFFF;
  margin-bottom: 10px;
  padding: 10px;
}

.ai_btn .ai_btn_con {
  width: 45%;
  background: #dfeaff;
  border-radius: 20px;
  display: flex;
  align-items: center;
  height: 40px;
  padding: 0 10px;
}
</style>
