<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"
      @search-change="searchChange"
      @search-reset="resetChange"
      @size-change="dataList"
      @current-change="dataList"
      @selection-change="selectionChange"
    >
      <template #usable="{ row }">
        <el-tag v-if="row.usable == '1'" type="success">已绑定</el-tag>
        <el-tag v-else type="info">未绑定</el-tag>
      </template>

      <template #productManager-form="{ row }">
        <!--        <el-select
          v-model="form.productManager"
          placeholder="产品负责人"
          filterable
        >
          <el-option
            v-for="item in userList"
            :key="item.userName"
            :label="item.userName"
            :value="item.userName"
          />
        </el-select>-->
        <el-tree-select
          v-model="form.productManager"
          :data="userList"
          filterable
        />
      </template>

      <!-- :disabled="row.usable == '1' ? false : true" -->
      <!--<template #menu-right="{}">
        <el-dropdown split-button
          >导入
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                @click="downloadTemplate('/api/v1/op/route/template')"
              >
                <i-ep-download />下载模板
              </el-dropdown-item>
              <el-dropdown-item @click="importExcelData">
                <i-ep-top />导入数据
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>-->
      <template #menu="{ row }">
        <el-button
          link
          type="primary"
          icon="el-icon-edit"
          v-if="
            row.usable === 0 &&
            (row.flowState === '0' ||
              row.flowState == '2' ||
              row.flowState == '-1')
          "
          @click="doEdit(row, index)"
          >编辑</el-button
        >
        <el-button
          link
          type="primary"
          icon="el-icon-edit"
          v-else
          @click="showProductManager(row, index)"
          >编辑</el-button
        >
        <el-button
          link
          type="danger"
          icon="el-icon-edit"
          v-if="
            row.usable === 0 &&
            (row.flowState === '0' ||
              row.flowState == '2' ||
              row.flowState == '-1')
          "
          @click="deleteRow(row, index)"
          >删除</el-button
        >
        <el-button
          link
          type="primary"
          v-if="row.upgradeVersion === '1'"
          icon="el-icon-notification"
          @click="changeLog(row)"
          >修改记录</el-button
        >
        <el-button
          link
          type="primary"
          v-if="row.isMain === '0'"
          icon="el-icon-setting"
          @click="setMain(row)"
          >主路线</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
        >
        <el-button
          link
          icon="el-icon-copy-document"
          :disabled="false"
          v-if="row.flowState === '1'"
          @click="copyRow(row)"
          >升版</el-button
        >
        <el-button
          link
          icon="el-icon-copy-document"
          @click="bindProcessPop(row)"
          v-if="row.flowState != '3'"
          >绑定</el-button
        >
      </template>
    </avue-crud>
    <CommonTable
      ref="ctableRef"
      tableTitle="添加产品"
      tableType="MARTERIAL"
      @selected-sure="onSelectedFinish"
    />
    <CommonTable
      ref="commonRef"
      tableTitle="选择通用工艺"
      tableType="ROUTE_COMMON"
      @selected-sure="onCommonFinish"
    />
    <ExcelUpload ref="uploadRef" @finished="uploadFinished" />
    <el-dialog
      v-model="centerDialogVisible"
      title="重命名"
      width="500"
      align-center
    >
      <el-form :model="tmpForm" label-width="auto" style="max-width: 800px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工艺路线编号">
              <el-input v-model="tmpForm.processRouteCode" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="工艺路线名称">
              <el-input v-model="tmpForm.processRouteName" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="renameRoute()"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="productManagerVisible"
      title="编辑产品负责人"
      width="500"
      align-center
    >
      <el-form
        :model="form"
        label-width="auto"
        style="max-width: 800px"
        :rules="rules"
      >
        <el-form-item label="产品负责人" prop="productManager">
          <!--          <el-select
            v-model="form.productManager"
            placeholder="产品负责人"
            filterable
          >
            <el-option
              v-for="item in userList"
              :key="item.userName"
              :label="item.userName"
              :value="item.userName"
            />
          </el-select>-->
          <el-tree-select
            v-model="form.productManager"
            :data="userList"
            filterable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="sureCancelProductManager">取消</el-button>
          <el-button type="primary" @click="sureToEditProductManager">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="dialog1.visible"
      :title="dialog1.title"
      width="900px"
      @close="dialog1.visible = false"
      :destroy-on-close="true"
    >
      <RouteChangeLog :targetRouteId="routeDeatil.id" />
    </el-dialog>
    <el-dialog
      v-model="dialog2.visible"
      :title="dialog2.title"
      width="900px"
      @close="dialog2.visible = false"
      :destroy-on-close="true"
    >
      <el-table
        :data="tableData"
        style="width: 100%"
        ref="singleTableRef"
        highlight-current-row
        @current-change="handleCurrentChange"
      >
        <el-table-column type="index" width="50" />
        <el-table-column prop="id" label="id" width="180" v-if="false" />
        <el-table-column
          prop="processRouteName"
          label="工艺路线名称"
          width="180"
        />
        <el-table-column
          prop="processRouteCode"
          label="工艺路线编码"
          width="180"
        />
        <el-table-column prop="processRouteVersion" label="版本" />
        <el-table-column prop="prodtName" label="产品名称" />
        <el-table-column prop="prodtModel" label="产品规格" width="180" />
      </el-table>
      <template #footer>
        <div class="footer">
          <el-button type="primary" @click="copyProcess()" :loading="isLoading"
            >复制</el-button
          >
          <el-button
            type="primary"
            @click="bindProcess(rowDetail)"
            :loading="loading"
            >自定义</el-button
          >
          <el-button @click="dialog2.visible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <LookFlowStep ref="LookFlowStepRef"></LookFlowStep>
    <work-flow-check
      ref="workFlowCheckRef"
      @sureToSave="onWFSave"
    ></work-flow-check>
  </div>
</template>
<script setup>
import { ref, getCurrentInstance } from "vue";
import { useCrud } from "@/hooks/userCrud";
import dictDataUtil from "@/common/configs/dictDataUtil";
import { useDictionaryStore } from "@/store";
import {
  copyList,
  copyProductRoute,
  copyRoute,
  editRouteWith,
  getMaxRouteVersion,
  updateMain,
} from "@/api/craft/route/index";
import { getUserTree } from "@/api/system/user/index";
import RouteChangeLog from "@/views/base/craftManagement/route/components/routeChangeLog.vue";
import { ElMessageBox } from "element-plus";
import WorkFlowCheck from "@/components/WorkFlows/workFlowCheck.vue";
import LookFlowStep from "@/views/flow/common/LookFlowStep.vue";
import { cancelFlow, submitFlow } from "@/api/flow";
const isLoading = ref(false);
const loading = ref(false);
// 数据字典相关
const { dicts } = useDictionaryStore();
const sureCancelProductManager = () => {
  productManagerVisible.value = false;
  dataList();
  form.value = {};
};
const tableData = ref([]);
const currentRow = ref();
const singleTableRef = ref(null);
const handleCurrentChange = (val) => {
  currentRow.value = val;
};
const setMain = (row) => {
  ElMessageBox.confirm("是否将该工艺路线设置为主路线？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    updateMain(row).then((data) => {
      ElMessage.success(data.msg);
      dataList();
    });
  });
};
const dialog1 = ref({
  title: "修改记录",
  visible: false,
});
const dialog2 = ref({
  title: "绑定",
  visible: false,
});
const routeData = ref({});
// 传入一个url，后面不带/
const { form, data, option, search, page, toDeleteIds, Methords, Utils } =
  useCrud({
    src: "/api/v1/op/route",
    afterAdd: (routeData) => {
      if (routeData.sourceRouteId) {
        router.push({
          path: `/base/craftManagement/bindProcess/${routeData.id}/${routeData.prodtCode}`,
        });
      }
    },
  });
const { dataList, createRow, updateRow, deleteRow, searchChange, resetChange } =
  Methords; //增删改查
const { selectionChange, multipleDelete } = Methords; //选中和批量删除事件
const { checkBtnPerm, downloadTemplate, exportData } = Utils; //按钮权限等工具
// checkBtnPerm(ButtonPermKeys.PLAN.BTNS.order_add) :permission="permission"
// const permission = reactive({
//   delBtn: checkPerm(buttonPermission.PLAN.BTNS.order_del),
//   addBtn: checkPerm(buttonPermission.PLAN.BTNS.order_add),
//   editBtn: checkPerm(buttonPermission.PLAN.BTNS.order_edit),
//   menu: true,
// });
const rowDetail = ref({});
let centerDialogVisible = ref(false);
const crudRef = ref(null); //crudRef.value 获取avue-crud对象
const tmpForm = ref({});

// 产品负责人相关
const userList = ref([]);
const currentPMRow = ref({});
const productManagerVisible = ref(false);
const showProductManager = (row, index) => {
  productManagerVisible.value = true;
  currentPMRow.value = row;
  form.value = row;
};
const rules = reactive({
  productManager: [
    { required: true, message: "产品管理员不能为空", trigger: "blur" },
  ],
});
const sureToEditProductManager = () => {
  editRouteWith(currentPMRow.value).then(() => {
    dataList();
    productManagerVisible.value = false;
    form.value = {};
  });
};

const copyProductProject = ref({});
const copyProcess = () => {
  if (!currentRow.value) {
    ElMessage.error("未选择要复制工艺路线!");
    return;
  }
  isLoading.value = true;
  loading.value = true;
  copyProductProject.value.sourceId = currentRow.value.id;
  copyProductProject.value.targetId = rowDetail.value.id;
  copyProductRoute(copyProductProject.value)
    .then((data) => {
      if (data.code === "200") {
        isLoading.value = false;
        loading.value = false;
        dialog2.value.visible = false;
        dataList();
        ElMessage.success(data.msg);
      }
    })
    .finally(() => {
      isLoading.value = false;
      loading.value = false;
    });
};
onMounted(() => {
  // console.log("crudRef", crudRef)
  dataList();
  getUserTree().then((data) => {
    userList.value = data.data;
  });
});

/**
 * 上传excel相关
 */
const uploadRef = ref(null);
const uploadFinished = () => {
  // 上传完成后的刷新操作
  page.currentPage = 1;
  dataList();
};
const routeDeatil = ref({});
const changeLog = (row) => {
  routeDeatil.value = row;
  dialog1.value.visible = true;
};
const doEdit = (row, index) => {
  row.prodtName1 = row.prodtName;
  crudRef.value && crudRef.value.rowEdit(row, index);
};
const importExcelData = () => {
  if (uploadRef.value) {
    uploadRef.value.show("/api/v1/op/route/import");
  }
};

// 选择产品相关
const ctableRef = ref(null);
const commonRef = ref(null);

const onSelectedFinish = (selectedValue) => {
  // search.value.prodtName = selectedValue.materialName;
  form.value.prodtName = selectedValue.materialName;
  form.value.prodtName1 = selectedValue.materialName;
  form.value.prodtCode = selectedValue.materialCode;
  form.value.prodtModel = selectedValue.spec;
};
const onCommonFinish = (selectedValue) => {
  form.value.commonRouteId = selectedValue.id;
  form.value.commonRouteName = selectedValue.processRouteName;
  form.value.commonRouteCode = selectedValue.processRouteCode;
};
const startChooseProduct = () => {
  if (ctableRef.value) {
    ctableRef.value.startSelect();
  }
};

const startChooseRoute = () => {
  if (ctableRef.value) {
    commonRef.value.startSelect();
  }
};
// 已经绑定了工序的可以复制，跟后端HT商量只传id即可。
const copyRow = (row) => {
  option.value.column.forEach((item) => {
    if (item.prop === "commonRouteCode" || item.prop === "commonRouteName") {
      item.display = false;
    }
  });
  if (row.usable == 0) {
    ElMessage.error("该路线未被绑定!");
    return;
  }
  getMaxRouteVersion(row.prodtCode).then((data) => {
    if (data.code === "200") {
      form.value = Object.assign(form.value, row);
      form.value.processRouteVersion = "";
      if (data.data) {
        form.value.processRouteVersion = (parseFloat(data.data) + 1).toFixed(1);
      }
      form.value.prodtName1 = row.prodtName;
      crudRef.value.rowAdd();
    }
  });
};
//  工作流相关 start
const workFlowCheckRef = ref(null);
const openCheckView = (row) => {
  row.businessId = row.id;
  workFlowCheckRef.value &&
    workFlowCheckRef.value.openDialog(row, "routeFlowService");
};
const LookFlowStepRef = ref(null);
const showFlowSteps = (row) => {
  LookFlowStepRef.value &&
    LookFlowStepRef.value.openFlowStepDrawer(row.flowIns);
};
const onCancelFlow = (row) => {
  console.log(row);
  cancelFlow({
    businessId: row.id,
    flowIns: row.flowIns,
  }).then(() => {
    ElMessage.success("撤销成功");
    dataList();
  });
};
const onWFSave = (flowForm) => {
  submitFlow(flowForm).then(() => {
    ElMessage.success("提交成功");
    workFlowCheckRef.value && workFlowCheckRef.value.close();
    dataList();
  });
};
//  工作流相关 end

const renameRoute = () => {
  tmpForm.value.id;
  tmpForm.value.processRouteCode;
  tmpForm.value.processRouteName;
  copyRoute(tmpForm.value).then(() => {
    tmpForm.value.id = undefined;
    tmpForm.value.processRouteCode = undefined;
    tmpForm.value.processRouteName = undefined;
    page.currentPage = 1;
    dataList();
  });
  centerDialogVisible.value = false;
};

const router = useRouter();
// 绑定工序
const bindProcess = (row) => {
  router.push({
    path: `/base/craftManagement/bindProcess/${row.id}/${row.prodtCode}`,
  });
};

const bindProcessPop = (row) => {
  if (row.routeData) {
    router.push({
      path: `/base/craftManagement/bindProcess/${row.id}/${row.prodtCode}/${row.usable}`,
    });
    return;
  }
  copyList(row).then((data) => {
    tableData.value = data.data;
    console.log(tableData.value);
    if (!tableData.value || tableData.value.length == 0) {
      router.push({
        path: `/base/craftManagement/bindProcess/${row.id}/${row.prodtCode}/${row.usable}`,
      });
      return;
    }
    rowDetail.value = row;
    dialog2.value.visible = true;
  });
};
// 设置表格列或者其他自定义的option
option.value = Object.assign(option.value, {
  searchEnter: true,
  selection: true,
  labelWidth: 150,
  menuWidth: 250,
  delBtn: false,
  searchLabelWidth: 110,
  editBtn: false,
  rowParentKey: "mainCode",
  column: [
    {
      label: "工艺路线名称",
      prop: "processRouteName",
      width: 150,
      search: true,
      overHidden: true,
      rules: [
        {
          required: true,
          message: "工艺路线名称不能为空",
          trigger: "blur",
        },
      ],
    },
    {
      label: "工艺路线编号",
      prop: "processRouteCode",
      search: true,
      width: 150,
      addDisplay: true,
      editDisabled: true,
      overHidden: true,
      display: false,
    },

    {
      label: "工艺路线类型",
      prop: "processRouteType",
      minWidth: 120,
      search: true,
      overHidden: true,
      rules: [
        {
          required: true,
          message: "工艺路线类型不能为空",
          trigger: "change",
        },
      ],
      type: "select",
      dicUrl: dictDataUtil.request_url + dictDataUtil.TYPE_CODE.routing_type,
      props: {
        label: "dictLabel",
        value: "dictValue",
      },
    },

    {
      label: "通用工艺id",
      prop: "commonRouteId",
      addDisplay: false,
      editDisplay: false,
      hide: true,
      width: 150,
      overHidden: true,
    },
    {
      label: "通用工艺名称",
      prop: "commonRouteName",
      editDisplay: false,
      width: 150,
      overHidden: true,
      click: () => {
        startChooseRoute();
      },
    },
    {
      label: "通用工艺编码",
      prop: "commonRouteCode",
      disabled: true,
      editDisplay: false,
      width: 150,
      overHidden: true,
    },
    {
      label: "执行文件和标准",
      prop: "executeFileStd",
      width: 180,
      addDisplay: true,
      editDisabled: false,
      overHidden: true,
      rules: [
        {
          required: true,
          message: "执行文件和标准不能为空",
          trigger: "blur",
        },
      ],
    },
    {
      label: "是否查看产品文档",
      prop: "documentShow",
      hide: true,
      type: "select",
      display: true,
      rules: [
        {
          required: true,
          trigger: "blur",
        },
      ],
      dicData: [
        {
          label: "是",
          value: 1,
        },
        {
          label: "否",
          value: 0,
        },
      ],
      value: 0,
    },
    {
      label: "产品名称",
      prop: "prodtName",
      overHidden: true,
      width: 150,
      search: true,
      editDisplay: false,
      addDisplay: false,
      rules: [
        {
          required: true,
          message: "请选择产品",
          trigger: "blur",
        },
      ],
    },
    {
      label: "产品名称",
      prop: "prodtName1",
      overHidden: true,
      hide: true,
      viewDisplay: false,
      width: 150,
      rules: [
        {
          required: true,
          message: "请选择产品",
          trigger: "blur",
        },
      ],
      readOnly: true,
      click: () => {
        startChooseProduct();
      },
      change: ({ value, column }) => {
        if (value != form.value.prodtName1) {
          startChooseProduct();
        }
      },
    },
    {
      label: "产品编号",
      prop: "prodtCode",
      overHidden: true,
      search: true,
      width: 150,
      disabled: true,
    },
    {
      label: "产品负责人",
      prop: "productManager",
      width: 120,
      slot: true,
      rules: [
        {
          required: true,
          message: "工艺路线类型不能为空",
          trigger: "change",
        },
      ],
    },
    {
      label: "产品型号",
      prop: "prodtModel",
      overHidden: true,
      search: true,
      minWidth: 200,
      disabled: true,
    },
    // 在产品那边绑定了工艺路线才是已绑定
    {
      label: "路线状态",
      prop: "usable",
      addDisplay: false,
      editDisplay: false,
      slot: true,
      width: 100,
      type: "radio",
      dicData: [
        {
          label: "已绑定",
          value: 1,
        },
        {
          label: "未绑定",
          value: 0,
        },
      ],
    },
    {
      label: "启用状态",
      prop: "enabled",
      addDisplay: false,
      editDisplay: false,
      slot: true,
      width: 100,
      type: "radio",
      dicData: [
        {
          label: "未启用",
          value: 1,
        },
        {
          label: "启用",
          value: 0,
        },
      ],
      value: 0,
    },
    {
      label: "流程状态",
      prop: "flowState",
      width: 120,
      search: true,
      addDisplay: false,
      editDisplay: false,
      overHidden: true,
      type: "select",
      dicUrl: dictDataUtil.request_url + dictDataUtil.TYPE_CODE.flow_ins_state,
      props: {
        label: "dictLabel",
        value: "dictValue",
      },
    },
    // 只有绑定了工序才可以复制。
    {
      label: "是否可复制",
      prop: "usable2",
      slot: true,
      width: 100,
      search: false,
      filterable: true,
      hide: true,
      addDisplay: false,
      editDisplay: false,
      type: "radio",
      dicData: [
        {
          label: "否",
          value: 0,
        },
        {
          label: "是",
          value: 1,
        },
      ],
      value: 0,
    },
    {
      label: "版本",
      prop: "processRouteVersion",
      addDisplay: true,
      editDisplay: true,
      type: "number",
      min: 1,
      value: 1.0,
      rules: [
        {
          required: true,
          message: "版本不能为空",
          trigger: "blur",
        },
      ],
      precision: 1,
    },

    {
      label: "来源版本",
      prop: "sourceVersion",
      display: false,
    },
    {
      label: "创建人",
      prop: "creator",
      addDisplay: false,
      editDisplay: false,
      overHidden: true,
    },
    {
      label: "创建时间",
      prop: "created",
      addDisplay: false,
      editDisplay: false,
      width: 150,
      overHidden: true,
    },
    {
      label: "主分支编码",
      prop: "mainCode",
      width: 150,
      hide: true,
      display: false,
    },
  ],
});
</script>
