<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      v-model="form"
      v-model:page="page"
      ref="crud"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template #menu-left>
        <el-button type="primary" @click="batchClose()">批量关闭</el-button>
        <!-- <el-upload :auto-upload="false" :show-file-list="false" action="action" :on-change="handleChange"
                    style="float: right;margin-left: 12px;">
                    <el-button type="primary">导入</el-button>
                </el-upload> -->
      </template>
      <template #menu-right> </template>

      <template #poCode="{ row }">
        <el-text type="primary">{{ row.poCode }}</el-text>
      </template>
      <template #prodIdent="{ row }">
        <el-tag>{{ row.prodIdent }}</el-tag>
      </template>
      <template #menu="{ row }">
        <el-button
          type="primary"
          text
          plain
          style="border: 0; background-color: transparent !important"
          @click="lookProcessRoute(row)"
          >工艺路线
        </el-button>

        <!-- <el-button type="primary" text plain style="border: 0; background-color: transparent !important"
                    @click.stop="glassDisc(row)">下发玻璃饼
                </el-button> -->
        <!-- <el-button type="primary" text plain style="border: 0; background-color: transparent !important"
                    @click.stop="rushFn(row)">加急
                </el-button> -->
        <!-- <el-button type="primary" text plain style="border: 0; background-color: transparent !important"
                    @click.stop="batchClose(row)">关闭
                </el-button> -->
        <!-- <el-button type="primary" text plain style="border: 0; background-color: transparent !important"
                    @click="inBatchesFn(row)">模具下发
                </el-button> -->
      </template>
    </avue-crud>

    <!-- 加急 -->
    <rushDialog :showDialog="isRushOpen" v-if="isRushOpen" @closeDialog="closeDialog"></rushDialog>

    <!-- 导入 -->
    <basic-import
      v-if="isShowImport"
      title="导入"
      :isShow="isShowImport"
      templateUrl="/blade-desk/QA/CycleTestItem/download-excel-template"
      templateName="试验项目模板.xls"
      importUrl="/blade-desk/QA/CycleTestItem/import-excel"
      @closeDialog="closeDialog"
    ></basic-import>
    <!-- 工艺路线弹窗 -->
    <lookProcess
      :is-open="isOpen"
      v-if="isOpen"
      @cancel="closeDialog"
      :rowData="rowItem"
      sourceId="sinTerOrder"
      :id="id"
      :checkPart="checkPart"
    ></lookProcess>
  </basic-container>
</template>

<script>
import {  closeBatchs,getShootList } from '@/api/orderManagement/sinTerPlanOrder';
import rushDialog from './components/rushDialog.vue';
import basicImport from '@/components/basic-import/main.vue';
import lookProcess from './components/lookProcess.vue';
import {
  add,
  getRole,
  getRoleAlias,
  getRoleTreeById,
  grant,
  grantTree,
  remove,
  update,
} from '@/api/system/role';
import { mapGetters } from 'vuex';
import { validatenull } from '@/utils/validate';

export default {
  components: {
    rushDialog,
    basicImport,
    lookProcess,
  },
  data() {
    return {
      id: null,
      isShowImport: false,
      inBatchesOpen: false,
      platingSmallOpen: false,
      planOrderArr: [],
      isOpen: false,
      rowItem: {},
      poId: null,
      form: {},
      box: false,
      props: {
        label: 'title',
        value: 'key',
      },
      menuGrantList: [],
      dataScopeGrantList: [],
      apiScopeGrantList: [],
      apiGrantList: [],
      menuTreeObj: [],
      dataScopeTreeObj: [],
      apiScopeTreeObj: [],
      selectionList: [],
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      option: {
        columnSort: true,
        tip: false,
        height: 'auto',
        calcHeight: 32,
        simplePage: false,
        searchShow: true,
        searchMenuSpan: 6,
        searchIcon: true,
        searchIndex: 3,
        tree: false,
        border: true,
        index: false,
        selection: true,
        viewBtn: false,
        addBtn: false,
        delBtn: false,
        editBtn: false,
        editBtnText: '修改',
        labelWidth: 120,
        // searchLabelWidth: 120,
        menuWidth: 100,
        dialogWidth: 900,
        dialogClickModal: false,
        searchEnter: true,
        excelBtn: false,
        filterBtn: true,
        searchShowBtn: false,
        excelBtn: true,
        showOverflowTooltip: true,
        addBtnIcon: ' ',
        viewBtnIcon: ' ',
        delBtnIcon: ' ',
        editBtnIcon: ' ',
        gridBtn: false,
        searchLabelPosition: 'left',
        searchLabelPosition: 'left',
        searchGutter: 24,
        searchSpan: 6,
        menuAlign: 'center',
        gridBtn: false,
        searchMenuPosition: 'right',
        align: 'center',

        column: [
          // {
          //     label: '是否确认',
          //     prop: 'poCode',
          //     search: true,
          //     sortable: true,
          //     width: 150,
          //     span: 12,
          //     headerAlign: 'center',
          //     align: 'center',
          //     rules: [
          //         {
          //             required: true,
          //             message: '请输入角色名称',
          //             trigger: 'blur',
          //         },
          //     ],
          // },
          {
            label: '计划单号',
            prop: 'ypCode',
            search: true,
            sortable: true,
            width: 150,
            span: 12,
            headerAlign: 'center',
            align: 'center',
            rules: [
              {
                required: true,
                message: '请输入计划单号',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '零件号',
            prop: 'partCode',
            search: true,
            sortable: true,
            width: 180,
            span: 12,
            headerAlign: 'center',
            align: 'center',

            rules: [
              {
                required: true,
                message: '请输入零件号',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '产品型号',
            prop: 'productType',
            search: false,
            sortable: true,
            disabled: true,
            width: 120,
            span: 12,
            headerAlign: 'center',
            align: 'center',
            rules: [
              {
                required: false,
                message: '请输入产品型号',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '产品名称',
            prop: 'productName',
            search: false,
            sortable: true,
            disabled: true,
            span: 12,
            width: 150,
            headerAlign: 'center',
            align: 'left',
            rules: [
              {
                required: false,
                message: '请输入产品名称',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '生产标识',
            prop: 'productIdent',
            search: false,
            sortable: true,
            width: 120,
            span: 12,
            headerAlign: 'center',
            align: 'center',
            rules: [
              {
                required: true,
                message: '请输入生产标识',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '使用部门',
            prop: 'useDept',
            search: false,
            sortable: true,
            disabled: true,
            width: 120,
            span: 12,
            headerAlign: 'center',
            align: 'center',
            rules: [
              {
                required: true,
                message: '请输入使用部门',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '生产数量',
            prop: 'ypQty',
            search: false,
            sortable: true,
            width: 120,
            span: 12,
            headerAlign: 'center',
            align: 'center',
            rules: [
              {
                required: true,
                message: '请输入生产数量',
                trigger: 'blur',
              },
            ],
          },

          // {
          //     label: '镀种',
          //     prop: 'plate',
          //     search: false,
          //     sortable: true,
          //     disabled: true,
          //     span: 12,
          //     headerAlign: 'center',
          //     align: 'center',
          //     rules: [
          //         {
          //             required: false,
          //             message: '请输入角色名称',
          //             trigger: 'blur',
          //         },
          //     ],
          // },
          // {
          //     label: '镀种小类',
          //     prop: 'plate',
          //     search: false,
          //     sortable: true,
          //     width: 120,
          //     display: false,
          //     span: 12,
          //     headerAlign: 'center',
          //     align: 'center',
          //     rules: [
          //         {
          //             required: true,
          //             message: '请输入角色名称',
          //             trigger: 'blur',
          //         },
          //     ],
          // },
          {
            label: '面积(d㎡)',
            prop: 'ypArea',
            search: false,
            sortable: true,
            width: 120,
            span: 12,
            disabled: true,
            headerAlign: 'center',
            align: 'center',
            rules: [
              {
                required: false,
                message: '请输入面积(d㎡)',
                trigger: 'blur',
              },
            ],
          },

          {
            label: '需求交期',
            prop: 'demandDate',
            search: false,
            sortable: true,
            width: 150,
            span: 12,
            headerAlign: 'center',
            align: 'center',

            rules: [
              {
                required: true,
                message: '请输入需求交期',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '备注',
            prop: 'memo',
            search: false,
            sortable: true,
            span: 24,
            type: 'textarea',
            width: 150,
            headerAlign: 'center',
            align: 'left',
            rules: [
              {
                required: true,
                message: '请输入备注',
                trigger: 'blur',
              },
            ],
          },

          {
            label: '计划员',
            prop: 'planUserName',
            search: false,
            sortable: true,
            width: 120,
            span: 12,
            headerAlign: 'center',
            align: 'center',
            rules: [
              {
                required: true,
                message: '请输入计划员',
                trigger: 'blur',
              },
            ],
          },

          {
            label: '计划下达时间',
            prop: 'releaseDate',
            search: false,
            sortable: true,
            searchLabelWidth: 100,
            width: 170,
            span: 12,
            type: 'date',
            headerAlign: 'center',
            align: 'center',
            rules: [
              {
                required: true,
                message: '请输入计划下达时间',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '订单状态',
            prop: 'status',
            search: true,
            sortable: true,
            span: 12,
            display: false,
            type: 'select',
            width: '140',
            headerAlign: 'center',
            align: 'center',
            dicData: [
              {
                value: 10001,
                label: '正常',
              },
              {
                value: 10002,
                label: '已退回',
              },
              {
                value: 10003,
                label: '无工艺',
              },
              {
                value: 10004,
                label: '已派工',
              },
              {
                value: 10005,
                label: '加工中',
              },
              {
                value: 10015,
                label: '已完工',
              },
              {
                value: 10021,
                label: '已关闭',
              },
            ],
          },
          {
            label: '已交付数量',
            prop: 'deliveryQty',
            search: false,
            sortable: true,
            span: 12,
            headerAlign: 'center',
            align: 'center',
            width: 170,
          },
          {
            label: '未交付数量',
            prop: 'undeliveredQty',
            search: false,
            sortable: true,
            span: 12,
            headerAlign: 'center',
            align: 'center',
            width: 170,
          },
          // {
          //     label: '异常类型',
          //     prop: 'createName',
          //     search: false,
          //     sortable: true,
          //     hide: true,
          //     span: 12,
          //     headerAlign: 'center',
          //     align: 'center',

          // },
        ],
      },

      data: [],
      isRushOpen: false,
      checkPart:"",
    };
  },
  computed: {
    ...mapGetters(['userInfo', 'permission']),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.role_add, false),
        viewBtn: this.validData(this.permission.role_view, false),
        delBtn: this.validData(this.permission.role_delete, false),
        editBtn: this.validData(this.permission.role_edit, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
    idsArray() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids;
    },
  },
  watch: {
    'form.currentAlias'() {
      const alias = this.form.currentAlias;
      if (!validatenull(alias)) {
        this.form.roleAlias = alias;
      }
    },
  },
  methods: {
    // 点击导入按钮
    handleImport() {
      this.isShowImport = true;
    },
    glassDisc() {
      this.$confirm('确定是否下达玻璃饼?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          // return remove(row.id);
        })
        .then(() => {
          // this.onLoad(this.page);
          // this.$message({
          //     type: 'success',
          //     message: '操作成功!',
          // });
        });
    },
    // 批量关闭
    batchClose() {
      // 检查是否选择了数据
      if (this.selectionList.length === 0) {
        this.$message.error('请选择至少一条数据');
        return;
      }
      let tmp = this.selectionList.filter(item => item.status === 10015 || item.status === 10021)
      if(tmp.length > 0){
        this.$message.error('请勿选择状态为【已完工】或【已关闭】的数据');
        return
      }
      this.$confirm('确定将选择数据批量关闭?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          const ids = this.selectionList.map(item => item.id).join(',');
          closeBatchs({ ...{ ids }, ...this.approveForm }).then(res => {
            if (res.data.code === 200) {
              this.$message.success('关闭成功');
              this.$refs.crud.toggleSelection();
              this.onLoad(this.page); // return remove(row.id);
            }
          });
          
        })
        .catch(() => {
          // this.onLoad(this.page);
          // this.$message({
          //     type: 'success',
          //     message: '操作成功!',
          // });
        });
    },
    // 加急
    rushFn() {
      this.isRushOpen = true;
    },
    closeDialog() {
      this.isRushOpen = false;
      this.isBatchOpen = false;
      this.isOpen = false;
    },
    inBatchesFn(row) {
      this.rowItem = row;
      this.inBatchesOpen = true;
    },
    subclass() {
      this.platingSmallOpen = true;
    },
    lookProcessRoute(row) {
      this.id = row.id;
      this.checkPart = row.partCode;
      this.isOpen = true;
      this.rowItem = row;
    },
    cancel(refresh) {
      if (refresh) {
        this.$refs.myTable.load();
      }
      this.inBatchesOpen = false;
      this.isOpen = false;
      this.planFormOpen = false;
      this.platingSmallOpen = false;
    },
    initData(roleId) {
      getRoleTreeById(roleId).then(res => {
        const column = this.findObject(this.option.column, 'parentId');
        column.dicData = res.data.data;
      });
    },
    submit() {
      const menuList = this.$refs.treeMenu.getCheckedKeys();
      const dataScopeList = this.$refs.treeDataScope.getCheckedKeys();
      const apiScopeList = this.$refs.treeApiScope.getCheckedKeys();
      grant(this.idsArray, menuList, dataScopeList, apiScopeList).then(() => {
        this.box = false;
        this.$message({
          type: 'success',
          message: '操作成功!',
        });
        this.selectionList = [];
        this.onLoad(this.page);
      });
    },
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          done();
        },
        error => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          done();
        },
        error => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },

    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    beforeOpen(done, type) {
      if (['add', 'edit'].includes(type)) {
        this.initData(this.form.id);
      }
      if (['edit', 'view'].includes(type)) {
        if (this.form.parentId === '0') {
          this.form.parentId = '';
        }
      }
      getRoleAlias().then(res => {
        const column = this.findObject(this.option.column, 'currentAlias');
        column.dicData = res.data.data;
      });
      done();
    },
    handleRole() {
      if (this.selectionList.length !== 1) {
        this.$message.warning('只能选择一条数据');
        return;
      }
      this.menuTreeObj = [];
      this.dataScopeTreeObj = [];
      this.apiScopeTreeObj = [];
      grantTree().then(res => {
        this.menuGrantList = res.data.data.menu;
        this.dataScopeGrantList = res.data.data.dataScope;
        this.apiScopeGrantList = res.data.data.apiScope;
        getRole(this.ids).then(res => {
          this.menuTreeObj = res.data.data.menu;
          this.dataScopeTreeObj = res.data.data.dataScope;
          this.apiScopeTreeObj = res.data.data.apiScope;
          this.box = true;
        });
      });
    },
    handleRowRole(row) {
      this.menuTreeObj = [];
      this.dataScopeTreeObj = [];
      this.apiScopeTreeObj = [];
      grantTree().then(res => {
        this.menuGrantList = res.data.data.menu;
        this.dataScopeGrantList = res.data.data.dataScope;
        this.apiScopeGrantList = res.data.data.apiScope;
        getRole(row.id).then(res => {
          this.menuTreeObj = res.data.data.menu;
          this.dataScopeTreeObj = res.data.data.dataScope;
          this.apiScopeTreeObj = res.data.data.apiScope;
          this.selectionList.push(row);
          this.box = true;
        });
      });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          this.$refs.crud.toggleSelection();
        });
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    handleChange(file, fileList) {
      // proxy.$Export.xlsx(file.raw).then((data) => {
      //     data.value = data.results;
      // });
      this.$message({
        type: 'success',
        message: '操作成功!',
      });
    },

    async onLoad(page, params = {}) {
      this.loading = true;
      try {
        const res = await getShootList({
          current:this.page.currentPage,
          size:this.page.pageSize,
          ...this.query
        })
        this.data = res.data.data.records;
        this.page.total = res.data.data.total;
        // const res = await getList(
        //   page.currentPage,
        //   page.pageSize,

        //   Object.assign(params, this.query)
        // );
        // if (res.code) {
        //   this.data = res.data.data.records;
        //   this.page.total = res.data.data.total;
        //   this.selectionClear();
        // }
      } catch (err) {
        console.log(err);
      }
      this.loading = false;
    },
  },
  mounted() {},
};
</script>
