<template>
  <div class="mainContentBox">
    <avue-crud
      ref="crudRef"
      v-model="form"
      v-model:page="page"
      v-model:search="search"
      :data="data"
      :option="option"
      @row-save="createRow"
      @row-update="updateRow"
      @row-del="deleteRow"
      @search-change="searchChange"
      @search-reset="resetChange"
      @size-change="dataList"
      @current-change="dataList"
      @selection-change="selectionChange"
    >
      <template #menu-left="{ size }">
        <el-button type="primary" @click="addTask">新增</el-button>
      </template>
      <template #menu="{ size, row, index }">
        <el-button @click="lookTask(row)" type="primary" link>查看</el-button>
        <el-button @click="updateTask(row)" type="primary" link>修改</el-button>
        <el-button @click="deleteTask(row.id)" type="danger" link
          >删除</el-button
        >
      </template></avue-crud
    >
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="850px"
      @close="dialog.visible = false"
      :key="formKey"
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
      >
        <el-form-item label="任务名称" prop="taskName">
          <el-input :disabled="lookStatus" v-model="ruleForm.taskName" />
        </el-form-item>
        <el-form-item label="物料名称" prop="materialName">
          <el-input
            :disabled="lookStatus"
            v-model="ruleForm.materialName"
            @click="open"
          />
        </el-form-item>
        <el-form-item label="物料编号" prop="materialNo">
          <el-input
            :disabled="lookStatus"
            v-model="ruleForm.materialNo"
            @click="open"
          />
        </el-form-item>

        <el-form-item label="工序编号" prop="operationCode">
          <el-input
            :disabled="lookStatus"
            v-model="ruleForm.operationCode"
            @click="openCode"
          />
        </el-form-item>
        <el-form-item label="是否启用" prop="state">
          <el-switch
            :disabled="lookStatus"
            v-model="ruleForm.state"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>

      <el-tabs v-model="activeName" class="demo-tabs">
        <el-tab-pane
          :label="'任务' + index"
          :name="`task` + index"
          v-for="(item, index) in 8"
          :key="index"
        >
          <FormItem ref="FormRef" :propIndex="index" />
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button v-if="!lookStatus" type="primary" @click="submit">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <CommonTable
      ref="ctableRef"
      tableTitle="BOM添加"
      tableType="MARTERIAL"
      @selected-sure="onSelectedFinish"
    />
    <CommonTable
      ref="ctableRef1"
      tableTitle="工艺选择"
      tableType="OPERATION"
      @selected-sure="onSelectedFinish1"
    />
  </div>
</template>
<script setup>
import { ref, getCurrentInstance } from "vue";
import { useCrud } from "@/hooks/userCrud";
import {
  addScrewdriverTask,
  updateScrewdriverTask,
  deleteScrewdriverTask,
} from "@/api/screwdriver";
import FormItem from "./components/formItem.vue";
const activeName = ref("task1");
const FormRef = ref([]);
const { form, data, option, search, page, toDeleteIds, Methords, Utils } =
  useCrud({
    src: "/api/v1/screwdriverTask",
  });
const { dataList, createRow, updateRow, deleteRow, searchChange, resetChange } =
  Methords; //增删改查
const { selectionChange, multipleDelete } = Methords;
const multipleRow = ref(true);
const ctableRef = ref(null);
const formKey = ref(false);
const ctableRef1 = ref(null);
const rules = {
  taskName: {
    required: true,
    trigger: "change",
  },
  materialName: {
    required: true,
    trigger: "change",
  },
  materialNo: {
    required: true,
    trigger: "change",
  },
  operationCode: {
    required: true,
    trigger: "change",
  },
  state: {
    required: true,
    trigger: "blur",
  },
};
const ruleFormRef = ref(null);
const arrayRef = ref([]);
const submit = async () => {
  arrayRef.value = [];
  FormRef.value.forEach((el, index) => {
    arrayRef.value.push(el.checkData(index + 1));
  });
  arrayRef.value.push(
    new Promise(async (resolve, reject) => {
      await ruleFormRef.value.validate((valid) => {
        if (valid) {
          resolve();
        } else {
          reject();
        }
      });
    })
  );
  Promise.allSettled(arrayRef.value).then(async (res) => {
    let errorArrayIndex = [];
    let form = false;
    for (let i = 0; i < res.length; i++) {
      if (res[i].status == "rejected") {
        if (i == 8) {
          form = true;
        } else {
          errorArrayIndex.push("任务" + res[i].reason);
        }
      }
    }
    if (errorArrayIndex.length > 0 || form == true) {
      //未校验成功逻辑
      let str = "请检查";
      if (errorArrayIndex.length > 0) {
        for (let i = 0; i < errorArrayIndex.length; i++) {
          if (i == errorArrayIndex.length - 1) {
            str += errorArrayIndex[i];
          } else {
            str += errorArrayIndex[i] + "、";
          }
        }
      }
      if (form == true) {
        str += "头部表单";
      }
      str += "选项";
      ElMessage.error(str);
    } else {
      //校验成功逻辑
      if (addStatus.value) {
        const { data, code } = await addScrewdriverTask({
          ...ruleForm.value,
          task0: FormRef.value[0].getFormData(),
          task1: FormRef.value[1].getFormData(),
          task2: FormRef.value[2].getFormData(),
          task3: FormRef.value[3].getFormData(),
          task4: FormRef.value[4].getFormData(),
          task5: FormRef.value[5].getFormData(),
          task6: FormRef.value[6].getFormData(),
          task7: FormRef.value[7].getFormData(),
        });
        formKey.value = !formKey.value;
        dialog.visible = false;
        if (code == "200") {
          ElMessage.success("操作成功");
          dataList();
        }
      } else {
        const { data, code } = await updateScrewdriverTask({
          ...ruleForm.value,
          task0: FormRef.value[0].getFormData(),
          task1: FormRef.value[1].getFormData(),
          task2: FormRef.value[2].getFormData(),
          task3: FormRef.value[3].getFormData(),
          task4: FormRef.value[4].getFormData(),
          task5: FormRef.value[5].getFormData(),
          task6: FormRef.value[6].getFormData(),
          task7: FormRef.value[7].getFormData(),
        });
        if (code == "200") {
          ElMessage.success("操作成功");
          dataList();
        }
        formKey.value = !formKey.value;
        dialog.visible = false;
      }
    }
  });
};
const open = () => {
  if (ctableRef.value) {
    ctableRef.value.startSelect();
  }
};
const openCode = () => {
  if (ctableRef1.value) {
    ctableRef1.value.startSelect();
  }
};
const onSelectedFinish = (selectedValueList) => {
  if (
    Object.keys(selectedValueList).length === 0 ||
    selectedValueList == undefined ||
    selectedValueList == null ||
    selectedValueList.length <= 0
  ) {
    ElMessage({
      message: "没有选择任何物料",
      type: "error",
    });
    return false;
  }
  ruleForm.value.materialName = selectedValueList.materialName;
  ruleForm.value.materialNo = selectedValueList.materialCode;
};
const onSelectedFinish1 = (selectedValueList) => {
  if (
    Object.keys(selectedValueList).length === 0 ||
    selectedValueList == undefined ||
    selectedValueList == null ||
    selectedValueList.length <= 0
  ) {
    ElMessage({
      message: "没有选择任何工序",
      type: "error",
    });
    return false;
  }
  ruleForm.value.operationCode = selectedValueList.operationCode;
};
const dialog = reactive({
  title: "设备选择",
  visible: false,
});
provide("dialog", dialog);
const ruleForm = ref({
  materialName: "",
  materialNo: "",
  state: 0,
  taskName: "",
  operationCode: "",
  task0: {},
  task1: {},
  task2: {},
  task3: {},
  task4: {},
  task5: {},
  task6: {},
  task7: {},
});
provide("ruleForm", ruleForm);
const addStatus = ref(false);
provide("addStatus", addStatus);
const lookStatus = ref(false);
provide("lookStatus", lookStatus);
const resetForm = () => {
  activeName.value = "task1";
  formKey.value = !formKey.value;
  ruleForm.value = {
    materialName: "",
    materialNo: "",
    state: 0,
    taskName: "",
    operationCode: "",
    task0: {},
    task1: {},
    task2: {},
    task3: {},
    task4: {},
    task5: {},
    task6: {},
    task7: {},
  };
};
const addTask = () => {
  resetForm();
  lookStatus.value = false;
  addStatus.value = true;
  dialog.title = "新增任务";
  dialog.visible = true;
};
const updateTask = (row) => {
  resetForm();
  lookStatus.value = false;
  addStatus.value = false;
  ruleForm.value = row;
  dialog.title = "编辑任务";
  dialog.visible = true;
};
const lookTask = (row) => {
  resetForm();
  addStatus.value = false;
  lookStatus.value = true;
  ruleForm.value = row;
  dialog.title = "查看任务";
  dialog.visible = true;
};
const deleteTask = async (id) => {
  const { code } = await deleteScrewdriverTask({ id });
  if (code == "200") {
    ElMessage.success("操作成功");
    dataList();
  }
};
option.value = Object.assign(option.value, {
  delBtn: false,
  addBtn: false,
  selection: false,
  labelWidth: 150,
  viewBtn: false,
  editBtn: false,
  column: [
    {
      label: "任务名称",
      prop: "taskName",
      addDisabled: true,
    },
    {
      label: "物料名称",
      prop: "materialName",
      addDisabled: true,
      display: false,
      search: true,
    },
    {
      label: "物料编号",
      addDisabled: true,
      prop: "materialNo",
      search: true,
    },
    {
      label: "工序编码",
      addDisabled: true,
      prop: "operationCode",
      search: true,
    },
    {
      label: "创建人",
      prop: "creator",
      display: false,
    },
    {
      label: "时间",
      prop: "created",
      display: false,
    },
  ],
});
onMounted(() => {
  dataList();
});
</script>
<style lang="scss" scoped></style>
