<template>
  <div class="ele-body">
    <el-card shadow="never">
      <!-- 搜索表单 -->
      <!-- <user-search @search="reload" /> -->
      <seek-page :seekList="seekList" @search="reload"></seek-page>

      <!-- 数据表格 -->
      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="datasource"
        :selection.sync="selection"
        row-key="id"
        :pageSize="this.$store.state.tablePageSize"
        @columns-change="handleColumnChange"
        :cache-key="cacheKeyUrl"
      >
        <!-- 表头工具栏 -->
        <template v-slot:toolbar>
          <el-button
            size="small"
            type="primary"
            icon="el-icon-plus"
            class="ele-btn-icon"
            @click="openEdit()"
            v-if="$hasPermission('main:producetask:save')"
          >
            新建
          </el-button>
          <el-button
            size="small"
            type="danger"
            icon="el-icon-delete"
            class="ele-btn-icon"
            @click="removeBatch"
            v-if="$hasPermission('main:producetask:delete')"
          >
            删除
          </el-button>
          <el-button
            size="small"
            type="primary"
            icon="el-icon-download"
            class="ele-btn-icon"
            plain
            v-if="$hasPermission('main:producetask:update')"
            @click="uploadFile()"
          >
            导入
          </el-button>
          <el-button
            size="small"
            type="primary"
            class="ele-btn-icon"
            @click="batchUpdateWorkCenter()"
          >
            批量修改工作中心
          </el-button>
        </template>

        <template v-slot:name="{ row }">
          <!-- <el-link v-if="row.type == 2" type="primary" :underline="false" @click="sampleParam(row)">
            {{ row.name }}
          </el-link>
          <span v-else> {{ row.name }}</span> -->
          {{ row.name }}
        </template>
        <!-- 状态列 -->

        <template v-slot:type="{ row }">
          {{ typeLabel(row.type) }}
        </template>

        <!-- 操作列 -->
        <template v-slot:action="{ row }">
          <el-link
            type="primary"
            :underline="false"
            icon="el-icon-edit"
            @click="openEdit(row)"
            v-if="$hasPermission('main:producetask:update')"
          >
            修改
          </el-link>
          <!-- <el-link type="primary" :underline="false" icon="el-icon-setting" @click="openSetting(row)">
            配置工艺参数
          </el-link> -->

          <el-popconfirm
            class="ele-action"
            title="确定要删除当前工序吗？"
            @confirm="remove(row)"
            v-if="$hasPermission('main:producetask:delete')"
          >
            <template v-slot:reference>
              <el-link type="danger" :underline="false" icon="el-icon-delete">
                删除
              </el-link>
            </template>
          </el-popconfirm>
        </template>
      </ele-pro-table>
    </el-card>
    <!-- 编辑弹窗 -->
    <user-edit
      :visible.sync="showEdit"
      :data="current"
      :controlList="controlList"
      @done="reload"
      ref="userEdit"
      :typeList="typeList"
    />
    <!-- 配置工艺参数 -->
    <user-setting
      :visible.sync="showSetting"
      :data="current"
      ref="userSetting"
    />

    <SampleParam
      v-if="sampleShow"
      :taskId="taskId"
      @close="close"
    ></SampleParam>

    <importDialog
      fileName="工艺_工序导入模板"
      apiUrl="/main/producetask/importExcel"
      fileUrl="/main/producetask/downLoadTemplate"
      ref="importDialogRef"
      @success="reload"
    />

    <WorkCenter ref="centerRefs" @changeCenter="determineChoose" />
  </div>
</template>

<script>
  import tabMixins from '@/mixins/tableColumnsMixin';
  import UserSearch from './components/user-search.vue';
  import UserEdit from './components/user-edit.vue';
  import UserSetting from './components/user-setting.vue';
  import SampleParam from './components/sampleParam.vue';
  import producetask from '@/api/technology/production';
  import control from '@/api/technology/control';
  import importDialog from '@/components/upload/comm-dialog.vue';
  import work from '@/api/technology/work';
  import WorkCenter from './components/WorkCenter.vue';

  export default {
    name: 'technologyProduction',
    mixins: [tabMixins],
    components: {
      UserSearch,
      UserEdit,
      UserSetting,
      SampleParam,
      importDialog,
      WorkCenter
    },
    data() {
      return {
        moudleName: 'mainProduceTask',
        // 表格列配置
        columns: [
          {
            columnKey: 'selection',
            type: 'selection',
            width: 45,
            align: 'center',
            fixed: 'left'
          },
          {
            prop: 'sort',
            label: '排序',
            align: 'center'
          },
          {
            prop: 'code',
            label: '工序编码',
            // sortable: 'custom',
            showOverflowTooltip: true,
            align: 'center',
            minWidth: 110
          },
          {
            slot: 'name',
            label: '工序名称',
            showOverflowTooltip: true,
            align: 'center',
            minWidth: 110
          },

          {
            slot: 'type',
            label: '工序类型',
            showOverflowTooltip: true,
            align: 'center',
            minWidth: 110
          },
          {
            align: 'center',
            prop: 'controlName',
            label: '工序控制码',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'workCenterName',
            label: '所属工作中心',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },

          {
            columnKey: 'action',
            label: '操作',
            width: 260,
            align: 'center',
            resizable: false,
            slot: 'action',
            showOverflowTooltip: true
          }
        ],
        // 表格选中数据
        selection: [],
        // 当前编辑数据
        current: null,
        // 是否显示编辑弹窗
        showEdit: false,
        // 是否显示参数弹窗
        showSetting: false,
        controlList: [],

        typeList: [
          {
            value: 1,
            label: '普通工序'
          },
          // {
          //   value: 2,
          //   label: '抽样质检'
          // },

          {
            value: 3,
            label: '抽样质检'
          },
          {
            value: 4,
            label: '包装工序'
          },
          {
            value: 6,
            label: '质检工序'
          },
          {
            value: 7,
            label: '生产准备'
          }
        ],

        sampleShow: false,
        taskId: null,
        cacheKeyUrl: 'abfad404-technology-production',
        controlListNewList: [], //给公共组件使用
        workCenterList: [] //工作中心列表
      };
    },
    computed: {
      seekList() {
        return [
          {
            label: '工序编码：',
            value: 'code',
            type: 'input',
            placeholder: ''
          },
          {
            label: '工序名称：',
            value: 'name',
            type: 'input',
            placeholder: ''
          },
          {
            label: '控制码：',
            value: 'controlId',
            type: 'select',
            placeholder: '',
            planList: this.controlListNewList
          },
          {
            label: '工序类型：',
            value: 'type',
            type: 'select',
            placeholder: '',
            planList: this.typeList
          },
          {
            label: '工作中心：',
            value: 'workCenterId',
            type: 'select',
            placeholder: '',
            planList: this.workCenterList
          }
        ];
      }
    },
    created() {
      this.getControlList();
      this.getListWorkCenter();
    },
    methods: {
      typeLabel(type) {
        return (
          this.typeList.find((m) => m.value == type) &&
          this.typeList.find((m) => m.value == type).label
        );
      },

      /*配置工艺参数 */
      openSetting(row) {
        this.current = row;
        this.showSetting = true;
      },
      /* 表格数据源 */
      async datasource({ page, limit, where, order }) {
        const res = await producetask.list({
          ...where,
          ...order,
          pageNum: page,
          size: limit
        });
        return res;
      },

      batchUpdateWorkCenter() {
        if (!this.selection.length) {
          this.$message.error('请至少选择一条数据');
          return;
        }
        this.$refs.centerRefs.open(this.selection[0]);
      },

      /* 刷新表格 */
      reload(where) {
        this.$refs.table.reload({ page: 1, where: where });
      },
      /* 打开编辑弹窗 */
      openEdit(row) {
        this.getControlList();
        this.current = row;
        this.showEdit = true;
        this.$refs.userEdit.$refs.form &&
          this.$refs.userEdit.$refs.form.clearValidate();
      },

      determineChoose(row) {
        if (row) {
          this.loading = true;
          this.selection.forEach((item) => {
            item.workCenterName = row.name;
            item.workCenterId = row.id;
          });

          producetask
            .bacthUpdate(JSON.parse(JSON.stringify(this.selection)))
            .then((res) => {
              if (res.code == 0) {
                this.$message.success('修改成功');
              }
              this.loading = false;
            })
            .catch((e) => {
              this.loading = false;
            });
        }

        // this.loading = true;
        // for (let i = 0; i < this.selection.length; i++) {
        //   this.selection[i].workCenterName = row.name;
        //   this.selection[i].workCenterId = row.id;
        //   producetask
        //     .save(this.selection[i])
        //     .then((msg) => {
        //       if (this.selection.length == i) {
        //         this.loading = false;
        //         this.$message.success('修改成功');
        //       }
        //     })
        //     .catch((e) => {
        //       this.loading = false;
        //       return;
        //     });
        // }
      },

      getControlList() {
        const params = {
          pageNum: 1,
          size: -1
        };
        control.list().then((res) => {
          this.controlList = res.list;
          this.controlListNewList = res.list.map((m) => ({
            label: m.name,
            value: m.id
          }));
        });
      },

      /* 删除 */
      remove(row) {
        const loading = this.$loading({ lock: true });

        producetask
          .delete([row.id])
          .then((msg) => {
            loading.close();
            // this.$message.success('删除成功');
            this.reload();
          })
          .catch((e) => {
            loading.close();
            // this.$message.error(e.message);
          });
      },
      /* 批量删除 */
      removeBatch() {
        if (!this.selection.length) {
          this.$message.error('请至少选择一条数据');
          return;
        }
        this.$confirm('确定要删除选中的工序吗?', '提示', {
          type: 'warning'
        })
          .then(() => {
            const loading = this.$loading({ lock: true });

            producetask
              .delete(this.selection.map((d) => d.id))
              .then((msg) => {
                // if(code=='0'){
                //   this.$message.success('删除成功');
                // }else{
                //   this.$message.error(msg.message);
                // }
                loading.close();

                this.reload();
              })
              .catch((e) => {
                loading.close();
                // this.$message.error(e.message);
              });
          })
          .catch(() => {});
      },

      sampleParam(row) {
        this.taskId = row.id;
        this.sampleShow = true;
      },

      close(done) {
        this.sampleShow = false;
      },
      uploadFile() {
        this.$refs.importDialogRef.open();
      },

      // 获取工作中心
      getListWorkCenter() {
        work.list({ pageNum: 1, size: -1 }).then((res) => {
          this.workCenterList = res.list.map((m) => ({
            label: m.name,
            value: m.id
          }));
        });
      }
    }
  };
</script>
