<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>
      </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"
          @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"
          @click="deleteRow(row, index)"
          >删除</el-button
        >
        <el-button
          link
          icon="el-icon-copy-document"
          :disabled="false"
          @click="copyRow(row)"
          >复制</el-button
        >
        <el-button link icon="el-icon-copy-document" @click="bindProcess(row)"
          >绑定</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-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>
  </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 { copyRoute, editRouteWith } from "@/api/craft/route/index";
import { getUserList } from "@/api/system/user/index";
// 数据字典相关
const { dicts } = useDictionaryStore();
const sureCancelProductManager = () => {
  productManagerVisible.value = false;
  dataList();
  form.value = {};
};
// 传入一个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({});

// 产品负责人相关
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 = {};
  });
};

onMounted(() => {
  // console.log("crudRef", crudRef)
  dataList();
  getUserList({}).then((data) => {
    userList.value = data.data;
  });
});

/**
 * 上传excel相关
 */
const uploadRef = ref(null);
const uploadFinished = () => {
  // 上传完成后的刷新操作
  page.currentPage = 1;
  dataList();
};

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[4].display = false;
  option.value.column[5].display = false;
  if (row.usable == 0) {
    ElMessage.error("该路线未被绑定!");
    return;
  }
  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}/${row.prodtCode}`,
  });
};

// 设置表格列或者其他自定义的option
option.value = Object.assign(option.value, {
  selection: true,
  labelWidth: 150,
  menuWidth: 250,
  delBtn: false,
  searchLabelWidth: 110,
  editBtn: false,
  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",
      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: true,
      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: "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,
      value: "1.0",
      rules: [
        {
          required: true,
          message: "版本不能为空",
          trigger: "blur",
        },
      ],
      precision: 1,
    },
    {
      label: "创建人",
      prop: "creator",
      addDisplay: false,
      editDisplay: false,
      overHidden: true,
    },
    {
      label: "创建时间",
      prop: "created",
      addDisplay: false,
      editDisplay: false,
      width: 150,
      overHidden: true,
    },
  ],
});
</script>
