<template>
  <div class="mainContentBox">
    <avue-form
      ref="formRef"
      v-model:search="search"
      v-model="form"
      :data="data"
      :option="option2"
      v-model:page="page"
      @row-save="createRow"
      @row-update="updateRow"
      @row-del="deleteRow"
      @search-change="searchChange"
      @size-change="dataList"
      @current-change="dataList"
      @selection-change="selectionChange"
    />
    <avue-crud
      ref="crudRef"
      v-model="form"
      :data="data"
      :option="option"
      v-model:page="page"
      @row-save="createRow"
      @row-update="updateRow"
      @row-del="deleteRow"
    >
      <template #menu-left="{ size }">
        <el-button type="primary" icon="el-icon-plus" circle @click="addSkill"
      /></template>
    </avue-crud>
    <el-dialog
      v-model="dialog1.visible"
      :title="dialog1.title"
      width="950px"
      @close="dialog1.visible = false"
    >
      <choice-item-page @material-info="materialInfo" :enabled="null" />
    </el-dialog>
    <el-dialog
      v-model="dialog2.visible"
      :title="dialog2.title"
      width="950px"
      @close="dialog2.visible = false"
    >
      <choice_out_materials @material-info="materialInfo" />
    </el-dialog>
    <div class="detail-footer">
      <el-button type="primary" @click="onHandle"> 确定 </el-button>
      <el-button @click="cancelWindow">取消</el-button>
    </div>
  </div>
</template>
<script setup>
import { ref, getCurrentInstance } from "vue";
import { useCrud } from "@/hooks/userCrud";
import { getAreaAndPlaceByCode, saveWmsOrder } from "@/api/storage";
import { useCommonStoreHook, useDictionaryStore } from "@/store";
import dictDataUtil from "@/common/configs/dictDataUtil";
const { isShowTable, tableType } = toRefs(useCommonStoreHook());
// 数据字典相关
const { dicts } = useDictionaryStore();

const data2 = ref(null);
// 传入一个url，后面不带/
const { form, data, option, search, page, toDeleteIds, Methords, Utils } =
  useCrud({
    src: "/api/v1/sys/skillScore",
  });
const emit = defineEmits(["closeDialog"]);
const cancelWindow = () => {
  emit("closeDialog", 11);
};

const {
  dataList,
  createRow,
  updateRow,
  deleteRow,
  searchChange,
  dataNoPageList,
} = Methords; //增删改查
const { selectionChange, multipleDelete } = Methords; //选中和批量删除事件
const { checkBtnPerm, downloadTemplate, exportData } = Utils; //按钮权限等工具
const formRef = ref(null);
const option2 = ref(null);
const ctableRef = ref(null); //crudRef.value 获取avue-crud对象
const router = useRouter();
const dialog1 = reactive({
  title: "物料选择",
  visible: false,
});
const dialog2 = reactive({
  title: "出库选择",
  visible: false,
});
onMounted(() => {
  /*  const bom = ref({
    batchCode: "",
    $cellEdit: true,
  });
  data.value.push(bom.value);*/
});
const addSkill = () => {
  const bom = ref({
    batchCode: "",
    $cellEdit: true,
  });
  data.value.push(bom.value);
};
const props = defineProps({
  dialog: {
    type: Object,
    default: () => {
      return {};
    },
  },
});
const materialInfo = (value) => {
  if (form.value.type === "4") {
    let item = {
      unit: value.unit,
      id: value.id,
      batchCode: value.batchCode,
      num: value.num,
      materialNo: value.materialNo,
      materialName: value.materialName,
      spec: value.spec,
      $cellEdit: true,
    };
    data.value[clickIndex.value] = item;
    dialog2.visible = false;
  } else {
    let item = {
      unit: value.unitDictValue,
      materialNo: value.materialCode,
      materialName: value.materialName,
      spec: value.spec,
      $cellEdit: true,
    };
    data.value[clickIndex.value] = item;
    dialog1.visible = false;
  }
};
const onHandle = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (data.value.length === 0) {
        ElMessage({
          message: "没有要保存数据",
          type: "error",
        });
        return false;
      }
      if (data.value.length > 0) {
        for (let i = 0; i < data.value.length; i++) {
          if (
            data.value[i].materialNo === undefined ||
            data.value[i].materialNo === null ||
            data.value[i].materialNo === ""
          ) {
            ElMessage({
              message: "第" + (i + 1) + "项没有选择物料",
              type: "error",
            });
            return false;
          }
          if (
            data.value[i].batchCode === undefined ||
            data.value[i].batchCode === null ||
            data.value[i].batchCode === ""
          ) {
            ElMessage({
              message: "第" + (i + 1) + "项没有输入批号",
              type: "error",
            });
            return false;
          }
          if (
            data.value[i].num === undefined ||
            data.value[i].num === null ||
            data.value[i].num === ""
          ) {
            ElMessage({
              message: "第" + (i + 1) + "项没有输入数量",
              type: "error",
            });
            return false;
          }
        }
      }
      //进行保存
      const saveData = { detailsList: data.value, ...form.value };
      saveData.vehicleCode = new Date().getTime();
      saveWmsOrder(saveData).then((res) => {
        ElMessage.success("操作成功");
        cancelWindow();
      });
    }
  });
};

const areaArray = ref([]);
const placeArray = ref([]);
const houseNoChange = async ({ value }) => {
  if (value) {
    let res = await getAreaAndPlaceByCode(value);
    areaArray.value = res.data;

    formRef.value.updateDic("locationNo", areaArray.value);
  }
};

const areaChange = async (obj) => {
  let places = obj?.item?.positions ?? [];
  placeArray.value = places;
  formRef.value.updateDic("coordinate", placeArray.value);
};

// 设置表格列或者其他自定义的option
option2.value = {
  selection: true,
  submitBtn: false,
  clearAbleBtn: false,
  emptyBtn: false,
  column: [
    {
      label: "操作类型",
      prop: "type",
      width: 60,
      overHidden: true,
      type: "select",
      search: true,
      change: () => {
        data.value = [];
      },
      rules: [
        {
          required: true,
          message: "操作类型不能为空",
          trigger: "trigger",
        },
      ],
      dicData: [
        { label: "原材料入库", value: "1" },
        { label: "工装入库", value: "2" },
        { label: "退料", value: "3" },
        { label: "出库", value: "4" },
      ],
    },
    {
      label: "仓库编码",
      prop: "houseNo",
      type: "select",
      search: true,
      width: 90,
      overHidden: true,
      editDisabled: true,
      dicUrl: dictDataUtil.request_url + dictDataUtil.TYPE_CODE.warehouse_type,
      props: {
        label: "dictLabel",
        value: "dictValue",
      },
      rules: [
        {
          required: true,
          message: "仓库编码不能为空",
          trigger: "trigger",
        },
      ],
      change: houseNoChange,
    },
    {
      label: "任务单号",
      width: 130,
      search: true,
      overHidden: true,
      prop: "taskNo",
      rules: [
        {
          required: true,
          message: "任务单号不能为空",
          trigger: "trigger",
        },
      ],
    },
    {
      label: "货区",
      width: 110,
      overHidden: true,
      type: "select",
      dictData: [],
      prop: "locationNo",
      props: {
        label: "area",
        value: "area",
      },
      rules: [
        {
          required: true,
          message: "货位不能为空",
          trigger: "trigger",
        },
      ],
      change: areaChange,
    },
    {
      label: "货位",
      overHidden: true,
      prop: "coordinate",
      type: "select",
      dictData: [],
      props: {
        label: "name",
        value: "name",
      },
      rules: [
        {
          required: true,
          message: "货位不能为空",
          trigger: "trigger",
        },
      ],
    },
  ],
};
const clickIndex = ref(0);

// 设置表格列或者其他自定义的option
option.value = Object.assign(option.value, {
  selection: false,
  addBtn: false,
  viewBtn: false,
  editBtn: false,
  saveBtn: false,
  search: false,
  cellBtn: true,
  menuWidth: 100,
  column: [
    {
      label: "物料编码",
      prop: "materialNo",
      readonly: true,
      cell: true,
      overHidden: true,
      click: ({ value, column, index }) => {
        clickIndex.value = index;
        if (!form.value.type) {
          ElMessage.error("请选择操作类型");
        } else {
          if (form.value.type === "4") {
            dialog2.visible = true;
          } else {
            dialog1.visible = true;
          }
        }
      },
    },
    {
      label: "物料名称",
      prop: "materialName",
      readonly: true,
      overHidden: true,
    },
    {
      label: "物料型号",
      prop: "spec",
      readonly: true,
      overHidden: true,
    },
    {
      label: "批次号",
      overHidden: true,
      prop: "batchCode",
      cell: true,
    },
    {
      label: "数量",
      prop: "num",
      type: "number",
      cell: true,
      min: 0,
      max: 99999,
    },
    {
      label: "单位",
      prop: "unit",
      width: 60,
    },
  ],
});
</script>
<style type="text/css">
.title-detail {
  width: 30%;
  height: 50px;
  line-height: 50px;
  margin: 25px 20px 25px 0;
  float: left;
}
.detail {
  margin: 0 auto;
  width: 100%;
}
.avue-crud {
  float: left;
}
.detail-footer {
  float: right;
  margin-top: 15px;
}
.el-select__selection {
  width: 150px;
}
</style>
