<!-- 应急物资分类表 -->
<template>
  <basic-container>
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      status-icon
      :disabled="props.type == 'look'"
    >
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="垂管局" prop="deptId">
            <el-select v-model="ruleForm.deptId" @change="changeCgj" clearable>
              <el-option
                v-for="item in cgjOption"
                :key="item.deptId"
                :label="item.abbreviationName"
                :value="item.deptId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="仓库名称" prop="warehouseId">
            <el-select v-model="ruleForm.warehouseId" clearable>
              <el-option
                v-for="item in cgjCkOption"
                :key="item.deptId"
                :label="item.abbreviationName"
                :value="item.deptId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="物资名称" prop="materialArr">
            <el-cascader
              :options="wzOptions"
              filterable
              v-model="ruleForm.materialArr"
              style="width: 100%"
              @change="changeWzmc"
              :props="{ value: 'id', label: 'name' }"
              placeholder="请选择物资名称"
              clearable
            ></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="入库日期" prop="inboundTime">
            <el-select v-model="ruleForm.inboundTime" clearable>
              <el-option
                v-for="(item, index) in rkrqAndDjOption"
                :key="index"
                :label="item.inboundTime"
                :value="item.inboundTime"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="单价" prop="unitPrice">
            <el-select v-model="ruleForm.unitPrice" clearable>
              <el-option
                v-for="(item, index) in rkrqAndDjOption"
                :key="index"
                :label="item.unitPrice"
                :value="item.unitPrice"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="问题数量" prop="quantity">
            <el-input v-model.number="ruleForm.quantity" @input="value => handleInput('quantity', value)" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="价值（万元）" prop="totalPrice">
            {{ decimalDev(decimalMul(ruleForm.unitPrice, ruleForm.quantity), 10000) || 0 }}
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="规格" prop="specs">
            <el-input v-model="ruleForm.specs" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="生产厂家" prop="manufacturer">
            <el-input v-model="ruleForm.manufacturer" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="问题描述" prop="description">
            <el-input v-model="ruleForm.description" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="建议处理方式" prop="method">
            <el-select v-model="ruleForm.method" clearable>
              <el-option v-for="(item, index) in jyclfsOption" :key="index" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="当前处理方式" prop="status">
            <el-select v-model="ruleForm.status" clearable>
              <el-option v-for="(item, index) in dqclfsOption" :key="index" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="ruleForm.remarks" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="operationbox">
      <el-button v-if="props.type != 'look'" type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
      <el-button @click="returnPage">返回</el-button>
    </div>
  </basic-container>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import type { FormInstance } from "element-plus";
import router from "@/router";
import { ElMessage } from "element-plus";
import {
  getDeptTypeListCgj,
  getDeptParentIdList,
  getTimeAndUnitPriceForFailure,
  insert,
  getData,
  update
} from "@/api/equipmentFailure";
import { dictTree } from "@/api/inAndOut/formationFilling/in";

import { decimalMul, decimalDev } from "@/global/decimalCompute";

import { getQuery } from "@/hooks/detailQuery/index";
const props = getQuery("/equipmentFailure/faultMngDetail");

export interface Department {
  deptId: string;
  abbreviationName: string;
}

const cgjOption = ref<Department[]>([]);
const cgjCkOption = ref<Department[]>([]);
const wzOptions = ref([]);
const rkrqAndDjOption = ref<{ inboundTime: string; unitPrice: string }[]>([]);
const jyclfsOption = [
  {
    value: "分批更换",
    label: "分批更换"
  },
  {
    value: "返厂维修",
    label: "返厂维修"
  },
  {
    value: "申请报废",
    label: "申请报废"
  }
];
const dqclfsOption = [
  {
    value: 0,
    label: "未完成"
  },
  {
    value: 1,
    label: "已完成"
  }
];

const ruleFormRef = ref<FormInstance>();
const ruleForm = ref({
  deptId: "",
  warehouseId: "",
  materialArr: [],
  inboundTime: "",
  unitPrice: "",
  quantity: "",
  totalPrice: "",
  specs: "",
  manufacturer: "",
  description: "",
  method: "",
  status: "",
  remarks: ""
});

const rules = reactive({
  deptId: [{ required: true, message: "请选择，不能为空", trigger: "change" }],
  warehouseId: [{ required: true, message: "请选择，不能为空", trigger: "change" }],
  materialArr: [{ required: true, message: "请选择，不能为空", trigger: "change" }],
  inboundTime: [{ required: true, message: "请选择，不能为空", trigger: "change" }],
  unitPrice: [{ required: true, message: "请选择，不能为空", trigger: "change" }],
  quantity: [{ required: true, message: "请填写，不能为空", trigger: "blur" }],
  manufacturer: [{ required: true, message: "请填写，不能为空", trigger: "blur" }],
  description: [{ required: true, message: "请填写，不能为空", trigger: "blur" }],
  method: [{ required: true, message: "请选择，不能为空", trigger: "change" }],
  status: [{ required: true, message: "请填写，不能为空", trigger: "change" }]
});

// 获取垂管局option
getDeptTypeListCgj().then((res: any) => {
  if (res.code === 0) {
    cgjOption.value = res.data;
  }
});
// 获取物资名称option
dictTree().then((res: any) => {
  if (res.code === 0) {
    wzOptions.value = res.data;
  }
});
// 选中垂管局后获取的仓库名称option
const changeCgj = async (item: string) => {
  const postData = {
    parentIdList: [item],
    deptType: 3
  };

  getDeptParentIdList(postData).then((res: any) => {
    if (res.code === 0) {
      cgjCkOption.value = res.data;
    }
  });
};
// 选中物质名称后获取的入库日期和单价option
const changeWzmc = (value: string) => {
  const postData = {
    materialGroup: value[0],
    materialType: value[1],
    materialName: value[2],
    materialUnit: value[3]
  };

  getTimeAndUnitPriceForFailure(postData).then((res: any) => {
    if (res.code === 0) {
      rkrqAndDjOption.value = res.data;
    }
  });
};

//提交方法
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      console.log(ruleForm.value);
      const { deptId, warehouseId, materialArr, unitPrice, quantity } = ruleForm.value;
      let postData = {
        ...ruleForm.value,
        deptName: cgjOption.value.find((item) => item.deptId === deptId)?.abbreviationName ?? "",
        warehouseName: cgjCkOption.value.find((item) => item.deptId === warehouseId)?.abbreviationName ?? "",
        materialGroup: materialArr[0],
        materialType: materialArr[1],
        materialName: materialArr[2],
        materialUnit: materialArr[3] ?? "",
        totalPrice: decimalDev(decimalMul(unitPrice, quantity), 10000) || 0
      };
      if ("materialArr" in postData) {
        delete postData.materialArr;
      }
      if (props.type == "edit") {
        update(postData).then((res: any) => {
          if (res.code === 0) {
            ElMessage({
              message: "修改成功！",
              type: "success"
            });
            returnPage();
          }
        });
      } else {
        insert(postData).then((res: any) => {
          if (res.code === 0) {
            ElMessage({
              message: "新增成功！",
              type: "success"
            });
            returnPage();
          }
        });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

const createdMth = async () => {
  if (props.id) {
    let { data } = await getData(props.id);
    changeCgj(data.deptId);
    const { materialGroup, materialType, materialName, materialUnit } = data;
    const materialArray = materialUnit
      ? [materialGroup, materialType, materialName, materialUnit]
      : [materialGroup, materialType, materialName];
    ruleForm.value = {
      ...data,
      materialArr: materialArray
    };
  }
};
createdMth();

type AllowedKeys = "quantity";

const handleInput = (name: AllowedKeys, value: string) => {
  const isPositiveInteger = /^[1-9]\d*$/.test(value);
  ruleForm.value[name] = isPositiveInteger ? String(Number(value)) : "";
};

/** 返回 */
const returnPage = () => {
  router.push({
    path: "/equipmentFailure/faultMng"
  });
};
</script>

<style lang="scss" scoped>
.operationbox {
  text-align: center;
  margin-top: 30px;
}
</style>
