<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 #menu-left="{ size }">
        <el-button
            :disabled="toDeleteIds.length < 1"
            type="refresh"
            icon="el-icon-refresh"
            :size="size"
            @click="apsSync"
        >APS同步</el-button
        >

      </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="danger"
          icon="el-icon-edit"
          v-if="row.usable === 0"
          @click="deleteRow(row, index)"
          >删除</el-button
        >
        <el-button
          link
          type="primary"
          icon="el-icon-copy-document"
          :disabled="false"
          @click="copyRow(row)"
          >复制</el-button
        >
        <el-button
          type="primary"
          link
          icon="el-icon-link"
          @click="bindProcess(row)"
          >绑定</el-button
        >
      </template>
    </avue-crud>
    <CommonTable
      ref="ctableRef"
      tableTitle="添加产品"
      tableType="MARTERIAL"
      @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>
  </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 } from "@/api/craft/route/index";
import {ElMessage, ElMessageBox} from "element-plus";
import {syncAps} from "@/api/aps";
// 数据字典相关
const { dicts } = useDictionaryStore();

const apsSync = () =>{
  ElMessageBox.confirm("是否同步所选中数据？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    let param = {type: 4,codes: toDeleteIds.value}
    syncAps(param).then((data)=>{
      if (data.code === "200") {
        ElMessage.success(data.msg);
      } else {
        ElMessage.error(data.msg);
      }
    })
  });
}

// 传入一个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)
  dataList();
});
const doEdit = (row, index) => {
  row.prodtName1 = row.prodtName;
  crudRef.value && crudRef.value.rowEdit(row, index);
};
/**
 * 上传excel相关
 */
const uploadRef = ref(null);
const uploadFinished = () => {
  // 上传完成后的刷新操作
  page.currentPage = 1;
  dataList();
};
const importExcelData = () => {
  if (uploadRef.value) {
    uploadRef.value.show("/api/v1/op/route/import");
  }
};

// 选择产品相关
const ctableRef = 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 startChooseProduct = () => {
  if (ctableRef.value) {
    ctableRef.value.startSelect();
  }
};
// 已经绑定了工序的可以复制，跟后端HT商量只传id即可。
const copyRow = (row) => {
  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}`,
    query: { prodtCode: row.prodtCode, routeId: row.id, usable: row.usable },
  });
};

// 设置表格列或者其他自定义的option
option.value = Object.assign(option.value, {
  selection: true,
  labelWidth: 100,
  editBtn: false,
  delBtn: false,
  menuWidth: 250,
  searchLabelWidth: 100,
  column: [
    {
      label: "工艺编号",
      prop: "processRouteCode",
      search: true,
      width: 150,
      addDisplay: true,
      editDisabled: true,
      overHidden: true,
      rules: [
        {
          required: true,
          message: "工艺编号不能为空",
          trigger: "blur",
        },
      ],
    },
    {
      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: "物料名称",
      prop: "prodtName",
      overHidden: true,
      width: 150,
      search: true,
      editDisplay: false,
      addDisplay: false,
      rules: [
        {
          required: true,
          message: "请选择物料",
          trigger: "blur",
        },
      ],
      readOnly: true,
    },
    {
      label: "物料名称",
      prop: "prodtName1",
      overHidden: true,
      width: 150,
      viewDisplay: false,
      hide: true,
      rules: [
        {
          required: true,
          message: "请选择物料",
          trigger: "blur",
        },
      ],
      readOnly: true,
      click: () => {
        startChooseProduct();
      },
    },
    {
      label: "物料编码",
      prop: "prodtCode",
      overHidden: true,
      search: true,
      width: 150,
      disabled: true,
    },
    {
      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,
      precision: 1,
      value: "1.0",
      rules: [
        {
          required: true,
          message: "请输入版本",
          trigger: "blur",
        },
      ],
    },
    {
      label: "创建人",
      prop: "creator",
      addDisplay: false,
      editDisplay: false,
      overHidden: true,
    },
    {
      label: "创建时间",
      prop: "created",
      addDisplay: false,
      editDisplay: false,
      width: 150,
      overHidden: true,
    },
  ],
});
</script>
