<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 #usable="{ row }">
        <el-tag v-if="row.usable == '1'" type="success">已绑定</el-tag>
        <el-tag v-else type="info">未绑定</el-tag>
      </template>-->

      <!-- :disabled="row.usable == '1' ? false : true" -->
      <template #productManager-form="{ row }">
        <el-tree-select
          v-model="form.productManager"
          :data="userList"
          filterable
        />
      </template>

      <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
          icon="el-icon-copy-document"
          :disabled="false"
          @click="copyRow(row)"
          v-if="row.routeData != null && row.routeData != ''"
          >复制</el-button
        >
        <el-button
          link
          type="primary"
          v-if="row.upgradeVersion === '1'"
          icon="el-icon-notification"
          @click="changeLog(row)"
          >修改记录</el-button
        >
        <el-button link icon="el-icon-copy-document" @click="bindProcess(row)"
          >绑定</el-button
        >
                <el-button
                  link
                  icon="el-icon-copy-document"
                  v-if="row.flowState == '0' || row.flowState == '2'"
                  @click="openCheckView(row)"
                  >提审</el-button
                >

                <el-button
                  link
                  icon="el-icon-copy-document"
                  v-if="row.flowState == '3'"
                  @click="onCancelFlow(row)"
                  >撤销</el-button
                >
      </template>
    </avue-crud>
    <CommonTable
      ref="ctableRef"
      tableTitle="添加产品"
      tableType="ROUTE_COMMON"
      @selected-sure="onSelectedFinish"
    />
    <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="dialog1.visible"
      :title="dialog1.title"
      width="900px"
      @close="dialog1.visible = false"
      :destroy-on-close="true"
    >
      <RouteChangeLog :targetRouteId="routeDeatil.id" />
    </el-dialog>

    <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 ButtonPermKeys from "@/common/configs/buttonPermission";
import dictDataUtil from "@/common/configs/dictDataUtil";
import { useDictionaryStore } from "@/store";
import { copyRoute } from "@/api/craft/route/index";
import { getUserTree } from "@/api/system/user/index";
import RouteChangeLog from "@/views/base/craftManagement/route/components/routeChangeLog.vue";
import WorkFlowCheck from "@/components/WorkFlows/workFlowCheck.vue";
import { cancelFlow } from "@/api/flow";

// 数据字典相关
const { dicts } = useDictionaryStore();

const testDebunce = () => {
  console.log("执行了事件");
};
const dialog1 = ref({
  title: "修改记录",
  visible: false,
});
// 传入一个url，后面不带/
const { form, data, option, search, page, toDeleteIds, Methords, Utils } =
  useCrud({
    src: "/api/v1/op/route",
  });
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,
// });
let centerDialogVisible = ref(false);
const crudRef = ref(null); //crudRef.value 获取avue-crud对象
const tmpForm = ref({});

onMounted(() => {
  // console.log("crudRef", crudRef)
  search.value.routeType = "common";
  dataList();
  getUserTree({}).then((data) => {
    userList.value = data.data;
  });
});
const changeLog = (row) => {
  console.log(row);
  routeDeatil.value = row;
  console.log(routeDeatil.value);
  dialog1.value.visible = true;
};
/**
 * 上传excel相关
 */
const uploadRef = ref(null);
const uploadFinished = () => {
  // 上传完成后的刷新操作
  page.currentPage = 1;
  search.value.routeType = "common";
  dataList();
};
const importExcelData = () => {
  if (uploadRef.value) {
    uploadRef.value.show("/api/v1/op/route/import");
  }
};

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

const userList = ref([]);

const onSelectedFinish = (selectedValue) => {
  // search.value.prodtName = selectedValue.materialName;
  form.value.prodtName = selectedValue.materialName;
  form.value.prodtCode = selectedValue.materialCode;
  form.value.prodtModel = selectedValue.spec;
};
const startChooseProduct = () => {
  if (ctableRef.value) {
    ctableRef.value.startSelect();
  }
};
// 已经绑定了工序的可以复制，跟后端HT商量只传id即可。
const copyRow = (row) => {
  form.value = Object.assign(form.value, row);
  form.value.processRouteVersion = "";
  crudRef.value.rowAdd();
};

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}/null`,
  });
};

// 设置表格列或者其他自定义的option
option.value = Object.assign(option.value, {
  searchEnter: true,
  selection: true,
  labelWidth: 130,
  searchLabelWidth: 110,
  column: [
    {
      label: "工艺路线编号",
      prop: "processRouteCode",
      search: true,
      width: 150,
      addDisplay: true,
      editDisabled: true,
      overHidden: true,
      display: false,
    },
    {
      label: "工艺路线名称",
      prop: "processRouteName",
      width: 150,
      search: true,
      overHidden: true,
      rules: [
        {
          required: true,
          message: "工艺路线名称不能为空",
          trigger: "blur",
        },
      ],
    },
    {
      label: "工艺路线类型",
      prop: "processRouteType",
      width: 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: "执行文件和标准",
      prop: "executeFileStd",
      width: 180,
      addDisplay: true,
      overHidden: true,
      rules: [
        {
          required: true,
          message: "执行文件和标准不能为空",
          trigger: "blur",
        },
      ],
    },
    // 在产品那边绑定了工艺路线才是已绑定
    {
      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: "productManager",
      width: 120,
      slot: true,
      rules: [
        {
          required: true,
          message: "工艺路线类型不能为空",
          trigger: "change",
        },
      ],
    },
    {
      label: "创建人",
      prop: "creator",
      addDisplay: false,
      editDisplay: false,
      overHidden: true,
    },
    {
      label: "创建时间",
      prop: "created",
      addDisplay: false,
      editDisplay: false,
      overHidden: true,
    },
    {
      label: "工艺路线类型",
      prop: "routeType",
      width: 150,
      hide: true,
      display: false,
      value: "common",
    },
  ],
});

//  工作流相关
const workFlowCheckRef = ref(null);
const openCheckView = (row) => {
  workFlowCheckRef.value &&
    workFlowCheckRef.value.openDialog(row.id, "routeFlowComService");
};
const onWFSave = () => {
  dataList();
};

const onCancelFlow = (row) => {
  console.log(row);
  cancelFlow({
    businessId: row.id,
    insId: row.flowIns,
  }).then(() => {
    ElMessage.success("撤销成功");
    dataList();
  });
};
</script>
