<template>
  <div class="mainContentBox">
    <avue-crud
      ref="crudRef"
      v-model:search="search"
      v-model="form"
      :data="data"
      :option="option"
      v-model:page="page"
      @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="add">新增</el-button></template
      >
      <template #menu="{ row, index, type }">
        <el-button
          link
          type="primary"
          size="small"
          @click="showSeq(row.seqNoList)"
          >查看管号</el-button
        >
        <el-button link type="primary" size="small" @click="showMaterial(row)"
          >采集替换</el-button
        >
        <el-button
          link
          type="danger"
          size="small"
          v-if="
            row?.flowState == '0' ||
            row?.flowState == '2' ||
            row?.flowState == '-1'
          "
          v-hasPerm="[ButtonPermKeys.PLAN.BTNS.filtersheet_del]"
          @click="deleteReplace(row.id)"
          >删除</el-button
        >
        <el-button
          link
          icon="el-icon-copy-document"
          v-if="
            row.flowState == '0' ||
            row.flowState == '2' ||
            row.flowState == '-1'
          "
          @click="openCheckView(row)"
          >提审</el-button
        >

        <el-button
          link
          v-if="row.flowState !== '0'"
          icon="el-icon-copy-document"
          @click="showFlowSteps(row)"
          >流程</el-button
        >

        <el-button
          link
          icon="el-icon-copy-document"
          v-if="row.flowState == '3'"
          @click="onCancelFlow(row)"
          >撤销</el-button
        >
      </template>
    </avue-crud>

    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="950px"
      :before-close="checkAll = false"
      @close="dialog.visible = false"
      style="padding-bottom: 40px"
    >
      <!-- <el-card
        style="cursor: pointer; font-size: 20px"
        shadow="always"
        :key="item"
        @click="toShowExcel(item)"
        v-for="item in showProList"
        >{{ item.formName }}</el-card
      > -->
      <el-form
        :model="formSeq"
        ref="formRef"
        label-width="auto"
        style="max-width: 800px"
      >
        <el-form-item
          label="工单编码"
          :rules="[
            {
              required: true,

              trigger: 'blur',
            },
          ]"
          prop="workOrderCode"
        >
          <el-select
            class="tep"
            :disabled="!addStatus"
            v-model="formSeq.workOrderCode"
            @click="dialog1.visible = true"
          />
        </el-form-item>
        <el-form-item
          label="工序名称"
          :rules="[
            {
              required: true,

              trigger: 'blur',
            },
          ]"
          prop="operationId"
        >
          <el-select
            filterable
            class="tep"
            v-model="formSeq.operationId"
            @change="setSeqList"
          >
            <el-option
              v-for="item in operations"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="管号"
          :rules="[
            {
              required: true,
              trigger: 'blur',
            },
          ]"
          seqNoList
          prop=""
        >
          <el-select
            class="tep"
            v-model="formSeq.seqNoList"
            multiple
            filterable
          >
            <template #header>
              <el-checkbox v-model="checkAll" @change="handleCheckAll">
                全选
              </el-checkbox>
              <span
                style="
                  margin: auto 10px auto 10px;
                  vertical-align: 2px;
                  font-weight: 200;
                "
              >
                管号总数: {{ options.length }}
              </span>
              <el-input
                v-model="toSelectStartCount"
                placeholder="请输入开始区间"
                class="selectInput"
                size="small"
              />
              <span style="margin: 0 0 0 10px">-</span>
              <el-input
                v-model="toSelectEndCount"
                placeholder="请输入结束区间"
                class="selectInput"
                size="small"
              >
              </el-input>
              <el-button
                type="primary"
                @click="startToSelectAheads"
                size="small"
                class="confirmBtn"
              >
                确定
              </el-button>
            </template>
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <div class="btns" style="float: right">
          <el-button type="primary" @click="submit">确定</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </el-form>
    </el-dialog>
    <el-dialog
      v-model="dialog1.visible"
      :title="dialog1.title"
      width="950px"
      @close="dialog1.visible = false"
    >
      <work-order-page @order-info="materialInfo1" />
    </el-dialog>
    <el-dialog
      v-model="dialog2.visible"
      :title="dialog2.title"
      width="950px"
      @close="dialog2.visible = false"
    >
      <el-card
        style="cursor: pointer; font-size: 20px"
        shadow="always"
        :key="item"
        v-for="item in showSeqList"
        >{{ item }}</el-card
      >
    </el-dialog>
    <el-dialog
      v-model="dialog3.visible"
      :title="dialog3.title"
      width="950px"
      @close="dialog3.visible = false"
      :destroy-on-close="true"
      append-to-body
    >
      <Replace
        :replaceId="replace.id"
        :dialog="dialog3"
        :flowState="replace.flowState"
      />
    </el-dialog>
    <LookFlowStep ref="LookFlowStepRef"></LookFlowStep>
    <WorkFlowCheck
      ref="workFlowCheckRef"
      @sureToSave="onWFSave"
    ></WorkFlowCheck>
  </div>
</template>
<script setup>
import { ref } from "vue";
import dictDataUtil from "@/common/configs/dictDataUtil";
import ButtonPermKeys from "@/common/configs/buttonPermission";
import { updateFilter } from "@/api/plan";
import Replace from "./components/replace-material.vue";
const replace = ref({});
import {
  addReplace,
  delReplace,
  getOperations,
  getReplace,
  getSeqList,
} from "@/api/replace";
import { useCrud } from "@/hooks/userCrud";
import WorkFlowCheck from "@/components/WorkFlows/workFlowCheck.vue";
import LookFlowStep from "@/views/flow/common/LookFlowStep.vue";
import { cancelFlow, submitFlow } from "@/api/flow";
const updateTitle = ref("筛选单详情");
const tableData = ref([]);
const formRef = ref(null);
const addStatus = ref(false);
const ExDataObj = ref({});
const workOderShow = ref(false);
const showProList = ref([]);
const showSeqList = ref([]);
const toSelectStartCount = ref(null);
const toSelectEndCount = ref(null);
const showSeq = (seqs) => {
  showSeqList.value = seqs;
  dialog2.visible = true;
};

const LookFlowStepRef = ref(null);
const showFlowSteps = (row) => {
  LookFlowStepRef.value &&
    LookFlowStepRef.value.openFlowStepDrawer(row.flowIns);
};

const onCancelFlow = (row) => {
  cancelFlow(row).then(() => {
    ElMessage.success("提交成功");
    dataList();
  });
};
const onWFSave = (flowForm) => {
  submitFlow(flowForm).then(() => {
    ElMessage.success("提交成功");
    workFlowCheckRef.value && workFlowCheckRef.value.close();
    dataList();
  });
};
const showMaterial = (row) => {
  replace.value = row;
  dialog3.visible = true;
};
const dialog = reactive({
  visible: false,
  title: "新增替换记录",
});
const workFlowCheckRef = ref(null);
const openCheckView = (row) => {
  row.businessId = row.id;
  workFlowCheckRef.value &&
    workFlowCheckRef.value.openDialog(row, "itemReplaceService");
};
const dialog1 = reactive({
  visible: false,
  title: "工单编码选择",
});
const dialog2 = reactive({
  title: "管号列表",
  visible: false,
});
const dialog3 = reactive({
  title: "物料替换",
  visible: false,
});
const submit = async () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (addStatus.value == true) {
        toAdd();
      } else {
        toEdiet();
      }
    } else {
      ElMessage.warning("请检查表单选项");
    }
  });
  toSelectStartCount.value = null;
  toSelectEndCount.value = null;
};
const closeShow = () => {
  workOderShow.value = false;
};
const resetForm = () => {
  formSeq.value.id = "";
  formSeq.value.seqNoList = [];
  formSeq.value.workOrderCode = "";
  formSeq.value.operationId = "";
  options.value = [];
  operations.value = [];
};
const toAdd = async () => {
  const { code } = await addReplace({ ...formSeq.value });
  if (code == "200") {
    ElMessage.success("新增成功");
    resetForm();
    dataList();
    dialog.visible = false;
  }
};
const { form, data, option, search, page, toDeleteIds, Methords, Utils } =
  useCrud({
    src: "/api/v1/processReplace",
  });
const { dataList, createRow, updateRow, deleteRow, searchChange, resetChange } =
  Methords; //增删改查
const { selectionChange, multipleDelete } = Methords; //选中和批量删除事件
const toEdiet = async () => {
  const { code } = await updateFilter({ ...formSeq.value });
  if (code == "200") {
    ElMessage.success("修改成功");
    resetForm();
    dataList();
    dialog.visible = false;
  }
};
const deleteReplace = async (id) => {
  const { code } = await delReplace({ id });
  if (code === "200") {
    ElMessage.success("删除成功");
    dataList();
  }
};
const options = ref([]);

const checkAll = ref(false);

const handleCheckAll = (val) => {
  if (val) {
    formSeq.value.seqNoList = options.value
      .filter((item) => !item.disabled)
      .map((item) => item.value);
  } else {
    formSeq.value.seqNoList = [];
  }
};

const searchRef = ref(null);
const formSeq = ref({ seqNoList: [] });
const materialInfo1 = async (value) => {
  formSeq.value.workOrderCode = value.workOrderCode;
  await setOperationList();
  formSeq.value.operationId = "";
  options.value = [];
  formSeq.value.seqNoList = [];
  dialog1.visible = false;
};
const operations = ref([]);
const setOperationList = async () => {
  const { data } = await getOperations(formSeq.value.workOrderCode);
  operations.value = [];
  formSeq.value.seqNoList = [];
  data.forEach((element) => {
    operations.value.push({
      value: element.operationId,
      label: element.operationName,
    });
  });
};

const setSeqList = async () => {
  formSeq.value.seqNoList = [];
  const { data } = await getSeqList(
    formSeq.value.workOrderCode,
    formSeq.value.operationId
  );
  options.value = [];
  data.sort((a, b) => a.seqNo.localeCompare(b.seqNo));
  data.forEach((element) => {
    options.value.push({
      value: element.seqNo,
      label: element.seqNo,
    });
  });
};

const add = () => {
  resetForm();
  addStatus.value = true;
  dialog.visible = true;
};

const cancel = () => {
  resetForm();
  dialog.visible = false;
  toSelectStartCount.value = null;
  toSelectEndCount.value = null;
};

const startToSelectAheads = () => {
    if (!Number(toSelectCount.value)) {
      ElMessage.error("请输入正确的数字");
      resetInput();
      return;
    }
    const count = Number(toSelectCount.value);
    const seqNoList = options.value.map((item) => item.value);
    formSeq.value.seqNoList = seqNoList.slice(0, count);
    if (options.value.length === 0) {
        ElMessage.error("请先选择工单和工序");
        toSelectStartCount.value = null;
        toSelectEndCount.value = null;
        return;
      }
    const start = Number(toSelectStartCount.value);
    const end = Number(toSelectEndCount.value);
    const seqListlength = seqNoList.length;
    if (Number.isInteger(start) && start > 0 && end === 0) {
      form.value.seqNoList = seqNoList.slice(start - 1, seqListlength);
      isAllChecked(form.value.seqNoList.length, seqNoList.length);
      return;
    }
    if (Number.isInteger(end) && end > 0 && start === 0) {
      form.value.seqNoList = seqNoList.slice(0, end);
      isAllChecked(form.value.seqNoList.length, seqNoList.length);
      return;
    }
    if (
      Number.isInteger(start) &&
      Number.isInteger(end) &&
      start > 0 &&
      end > 0
    ) {
      form.value.seqNoList = seqNoList.slice(start - 1, end);
      isAllChecked(form.value.seqNoList.length, seqNoList.length);
      return;
    }
};

const isAllChecked = (choseLength, seqLength) => {
  if (choseLength === seqLength) {
    checkAll.value = true;  } else {
    checkAll.value = false;
  }
};
onMounted(() => {
  dataList();
});

// 设置表格列或者其他自定义的option
option.value = Object.assign(option.value, {
  searchEnter: true,
  selection: false,
  addBtn: false,
  delBtn: false,
  editBtn: false,
  viewBtn: false,
  column: [
    {
      label: "生产批号",
      prop: "workOrderCode",
      editDisabled: true,
      overHidden: true,
      search: true,
    },
    {
      label: "产品名称",
      prop: "materialName",
      editDisabled: true,
      search: true,
    },
    {
      label: "产品编码",
      prop: "materialCode",
      editDisabled: true,
      search: true,
    },
    {
      label: "产品规格",
      prop: "materialModel",
      search: true,
      overHidden: true,
    },
    {
      label: "订单编号",
      prop: "orderCode",
    },
    {
      label: "工序名称",
      prop: "operationName",
    },

    {
      label: "创建人",
      prop: "creator",
      editDisplay: false,
    },
    {
      label: "创建时间",
      prop: "created",
    },
    /*{
      label: "日期",
      prop: "createdSearch",
      width: 160,
      type: "daterange",
      searchRange: true,
      display: false,
      hide: true,
      startPlaceholder: "开始范围",
      endPlaceholder: "结束范围",
      format: "YYYY-MM-DD",
      valueFormat: "YYYY-MM-DD",
      overHidden: true,
      search: true,
    },*/
  ],
});
</script>

<style lang="scss" scoped>
.btns {
  margin-bottom: 10px;
}
.selectInput {
  width: 20%;
  margin: 0 0 8px 10px;
}
.confirmBtn {
  margin: 0 0 8px 10px;
  height: 22px;
}
</style>
