<template>
  <div class="pt40 pl30" style="width: 600px">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleFormRef"
      label-width="140px"
      label-position="left"
    >
      <el-form-item class="mb30" prop="securityCheckName" label="安检名称">
        <el-input
          style="width: 280px"
          v-model="ruleForm.securityCheckName"
        ></el-input>
      </el-form-item>
      <el-form-item class="mb30" prop="securityCheckTarget" label="安检目标">
        <el-input
          style="width: 280px"
          v-model="ruleForm.securityCheckTarget"
        ></el-input>
      </el-form-item>
      <el-form-item class="mb30" prop="securityCheckFocus" label="排查重点">
        <el-input
          style="width: 280px"
          v-model="ruleForm.securityCheckFocus"
        ></el-input>
      </el-form-item>
      <el-form-item class="mb30" prop="shipLength" label="选择适用船长">
        <div class="df aic" style="width: 100%">
          <el-input
            style="width: 130px"
            v-model="ruleForm.minShipLen"
            :disabled="ruleForm.isAllShip === 1"
          ></el-input>
          <div class="mr10 ml10">-</div>
          <el-input
            style="width: 130px"
            v-model="ruleForm.maxShipLen"
            :disabled="ruleForm.isAllShip === 1"
          ></el-input>
          <el-checkbox
            class="ml20"
            v-model="ruleForm.isAllShip"
            label="所有船舶"
            size="large"
            :true-value="1"
            :false-value="0"
            :true-label="1"
            :false-label="0"
          />
        </div>
      </el-form-item>
      <div class="df aic jcsb mb20 mt50">
        <el-button class="mr30" type="primary" @click="addNewItem">
          添加新检查项目
        </el-button>
        <el-button-group v-show="ruleForm.items.length > 1">
          <el-button
            v-for="(item, index) in ruleForm.items"
            @click="itemIndex = index"
            :type="itemIndex == index ? 'primary' : ''"
          >
            {{ item.checkItemName || "新检查项目" }}
          </el-button>
        </el-button-group>
      </div>
      <el-form-item class="mb30" label="项目名称" prop="checkItemName">
        <el-input
          style="width: 280px"
          v-model="ruleForm.items[itemIndex].checkItemName"
        ></el-input>
      </el-form-item>
      <el-form-item class="mb30" label="项目类型" prop="checkItemTypeName">
        <el-select
          style="width: 280px"
          v-model="ruleForm.items[itemIndex].checkItemTypeName"
          value-key="checkItemTypeName"
          placeholder="请选择安全检查项目类型"
          @change="selectChange"
        >
          <el-option
            v-for="item in templateTypeSelect"
            :label="item.value"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item class="mb30" label="项目备注" prop="checkItemRemark">
        <el-input
          style="width: 280px"
          v-model="ruleForm.items[itemIndex].checkItemRemark"
        ></el-input>
      </el-form-item>
      <div class="df jcfe">
        <el-button
          v-show="ruleForm.items.length > 1"
          size="small"
          type="primary"
          @click="removeItem"
        >
          移除当前项目
        </el-button>
      </div>
    </el-form>
    <div class="dialog-footer df aic jcfe">
      <el-button @click="resetForm">重置</el-button>
      <el-button type="primary" @click="addFireSafetyTemplate(ruleForm)">
        确定
      </el-button>
    </div>
  </div>
</template>
<script setup>
import { ref, h, reactive, toRefs, onMounted } from "vue";
import { ElNotification, ElMessageBox, ElMessage } from "element-plus";
import store from "../../store";
import router from "../../router";
import md5 from "md5";
import api from "../../apis/fetch";
import { useRoute } from "vue-router";
import _ from "lodash";
import { subTimeStr } from "../../utils/utils";

const route = useRoute();
async function getFireSafetyTemplateDetail(id) {
  let { data } = await api.getFireSafetyTemplateDetail({
    id,
  });
  if (data.status == 0) {
    ruleForm.value = data.result;
  }
}
let ruleFormRef = ref(null);
let ruleForm = ref({
  securityCheckName: "",
  items: [{}],
  minShipLen: "",
  maxShipLen: "",
  isAllShip: 0,
});

async function resetForm() {
  itemIndex.value = 0;
  ruleForm.value = {
    items: [{}],
  };
  if (route.query.id) getFireSafetyTemplateDetail(route.query.id);
}

const checkShipLength = (rule, value, callback) => {
  if (
    (!ruleForm.value.minShipLen || !ruleForm.value.maxShipLen) &&
    ruleForm.value.isAllShip === 0
  ) {
    callback(new Error("请完善适用船长"));
  } else {
    callback();
  }
};

const checkItemName = (rule, value, callback) => {
  if (
    !ruleForm.value.items.every((item, index) => {
      if (!item.checkItemName)
        callback(new Error(`请完善第${index + 1}个项目名称`));
      return !!item.checkItemName;
    })
  ) {
  } else {
    callback();
  }
};
const checkItemTypeName = (rule, value, callback) => {
  if (
    !ruleForm.value.items.every((item, index) => {
      if (!item.checkItemTypeName)
        callback(new Error(`请完善第${index + 1}个项目类型`));
      return !!item.checkItemTypeName;
    })
  ) {
  } else {
    callback();
  }
};
const checkItemRemark = (rule, value, callback) => {
  if (
    !ruleForm.value.items.every((item, index) => {
      if (!item.checkItemRemark)
        callback(new Error(`请完善第${index + 1}个项目备注`));
      return !!item.checkItemRemark;
    })
  ) {
  } else {
    callback();
  }
};

const rules = ref({
  securityCheckName: [
    { required: true, message: "请填写安检名称", trigger: "blur" },
  ],
  securityCheckTarget: [
    { required: true, message: "请填写安检目标", trigger: "blur" },
  ],
  securityCheckFocus: [
    { required: true, message: "请填写安检重点", trigger: "blur" },
  ],
  shipLength: [{ validator: checkShipLength, trigger: "blur" }],
  checkItemName: [{ validator: checkItemName, trigger: "blur" }],
  checkItemTypeName: [{ validator: checkItemTypeName, trigger: "blur" }],
  checkItemRemark: [{ validator: checkItemRemark, trigger: "blur" }],
});
let itemIndex = ref(0);
let templateTypeSelect = ref([]);
function addNewItem() {
  ruleForm.value.items.push({});
  itemIndex.value = ruleForm.value.items.length - 1;
}
async function getFireSafetyTemplateTypeSelect() {
  let { data } = await api.getFireSafetyTemplateTypeSelect();
  templateTypeSelect.value = data.status == 0 ? data.result : [];
}
async function addFireSafetyTemplate() {
  ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      let {
        securityCheckName,
        minShipLen,
        maxShipLen,
        items,
        id,
        securityCheckTarget,
        securityCheckFocus,
        isAllShip,
      } = ruleForm.value;
      let postData = {
        securityCheckName,
        minShipLen,
        maxShipLen,
        items,
        id,
        securityCheckTarget,
        securityCheckFocus,
        isAllShip,
      };

      const loading = ElLoading.service({
        lock: true,
        text: "正在提交...",
        background: "rgba(0, 0, 0, 0.7)",
      });

      let res = await api[
        id ? "updateFireSafetyTemplate" : "addFireSafetyTemplate"
      ](postData);
      loading.close();
      if (res.data.status == 0) {
        ElNotification.success({
          title: id ? "更新成功" : "添加成功",
          duration: 1500,
          message: `${securityCheckName}:${res.data.msg}`,
          type: "success",
        });
        router.replace("/fireSafetyManage/fireSafetyTemplateList");
      } else {
        ElNotification.error({
          title: "失败",
          duration: 2000,
          message: res.data.msg,
        });
      }
    } else {
      return false;
    }
  });
}

function removeItem() {
  ruleForm.value.items.splice(itemIndex.value, 1);
  itemIndex.value = itemIndex.value == 0 ? 0 : itemIndex.value - 1;
}

function selectChange(e) {
  ruleForm.value.items[itemIndex.value].checkItemTypeId = e.key;
  ruleForm.value.items[itemIndex.value].checkItemTypeName = e.value;
}

onMounted(() => {
  if (route.query.id) getFireSafetyTemplateDetail(route.query.id);
  getFireSafetyTemplateTypeSelect();
});
</script>

<style scoped>
.dialog-footer {
  margin-top: 100px;
}
</style>
