<template>
  <div class="ele-body">
    <el-card shadow="never" v-loading="loading">
      <order-search @search="reload" ref="searchRef"> </order-search>
      <!--      <el-tabs v-model="activeName" type="card">
        <el-tab-pane label="未完成工单" name="first"></el-tab-pane>
        <el-tab-pane label="已完成工单" name="second"></el-tab-pane>
      </el-tabs> -->
      <!-- 数据表格 -->
      <ele-pro-table
        ref="table"
        :columns="newColumns"
        :datasource="datasource"
        cache-key="workOrderTable"
        @sort-change="onSortChange"
        height="calc(100vh - 380px)"
      >
        <template v-slot:code="{ row }">
          {{ row.code }}
        </template>

        <template v-slot:formingWeight="{ row }">
          {{ row.formingWeight }} {{ row.newWeightUnit }}
        </template>

        <template v-slot:priority="{ row }">
          <div style="display: flex">
          <el-input
            v-model="row.priority"
            type="number"
            size="mini"
            :min="0"
            :max="10"
            @change="priorityChange(row)"
             style="width: 80px"
          ></el-input>
          <el-popover
            placement="right"
            width="200"
            trigger="hover"
            content="数值越大优先级越高（0-3普通, 4-6优先, 7-10紧急）"
          >
            <div class="sort-wrap" slot="reference">
              <i class="el-icon-caret-top" @click="sortTop(row)"></i>
              <i class="el-icon-caret-bottom" @click="sortBottom(row)"></i>
            </div>
          </el-popover>
          </div>
        </template>

        <template v-slot:status="{ row }">
          <span :class="{ 'ele-text-danger': row.status == 3 }">
            {{ statusFormatter(row.status) }}
          </span>
        </template>
        <!-- 操作列 -->
        <template v-slot:action="{ row }">
          <el-link
            type="primary"
            :underline="false"
            icon="el-icon-truck"
            @click="toRelease(row)"
            v-if="
              (clientEnvironmentId != '4' && row.status == 8) ||
              (clientEnvironmentId == '4' &&
                !row.productName.includes('板材') &&
                row.status == 8)
            "
          >
            派单
          </el-link>
        </template>
      </ele-pro-table>
    </el-card>

    <el-dialog :visible.sync="visible" title="选择班组" width="400px">
      <el-select v-model="releasParams.teamId">
        <el-option
          v-for="item in teamList"
          :value="item.id"
          :key="item.id"
          :label="item.name"
        ></el-option>
      </el-select>

      <el-radio-group v-model="singleReport" style="margin-top: 16px;">
        <el-radio :label="1">单件报工</el-radio>
        <el-radio :label="0">批量报工</el-radio>
      </el-radio-group>

      <div class="footer" slot="footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getList,
    releaseWorkOrder,
    updatePriority
  } from '@/api/workOrder/index.js';
  import { teamPage } from '@/api/mainData/index.js';
  import OrderSearch from './components/order-search.vue';

  import { fieldModel } from '@/api/saleOrder';

  import { debounce } from 'lodash';
  export default {
    components: {
      OrderSearch
    },
    data() {
      return {
        visible: false,
        loading: false,
        releasParams: {
          teamId: '',
          id: ''
        },

        singleReport: 1,
        teamList: [],

        statusOpt: [
          { label: '待生产', value: 4 },
          { label: '生产中', value: 5 },
          { label: '待下达', value: 8 }
        ],

        newColumns: [],

        current: null
      };
    },
    computed: {
      clientEnvironmentId() {
        return this.$store.state.user.info.clientEnvironmentId;
      },
      // 表格列配置
      columns() {
        return [
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            showOverflowTooltip: true,
            fixed: 'left'
          },
          {
            slot: 'code',
            label: '生产订单号',
            align: 'center',
            minWidth: 110,
            sortable: true
          },
          {
            prop: 'productionPlanCode',
            label: '计划编号',
            align: 'center'
          },
          {
            prop: 'produceRoutingName',
            label: '工艺路线',
            align: 'center'
          },
          {
            prop: 'productCode',
            label: '产品编码',
            align: 'center'
          },
          {
            prop: 'productName',
            label: '产品名称',
            align: 'center'
          },
          {
            prop: 'brandNo',
            label: '牌号',
            align: 'center'
          },

          {
            prop: 'batchNo',
            label: '批次号',
            align: 'center',
            minWidth: 100,
            showOverflowTooltip: true
          },
          {
            prop: 'model',
            label: '型号',
            align: 'center'
          },

          {
            prop: 'priority',
            label: '优先级',
            align: 'center',
            minWidth: 120,
            slot: 'priority',
            sortable: 'custom'
          },


          {
            prop: 'formingNum',
            label: '要求生产数量',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'formingWeight',
            label: '要求生产重量',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110,
            slot: 'formingWeight'
          },
          {
            prop: 'planStartTime',
            label: '计划开始时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },

          {
            prop: 'planCompleteTime',
            label: '计划结束时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },

          {
            prop: 'createTime',
            label: '创建时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            slot: 'status',
            label: '状态',
            align: 'center',
            formatter: (row) => {
              const obj = this.statusOpt.find((i) => i.value == row.status);
              return obj && obj.label;
            }
          },

          {
            prop: 'serialNo',
            label: '客户代号',
            align: 'center',
            showOverflowTooltip: true
          },

          {
            prop: 'simpleName',
            label: '客户简称',
            align: 'center',
            showOverflowTooltip: true
          }
        ];
      }
    },
    created() {
      this.getFieldModel();
    },
    methods: {
      statusFormatter(status) {
        const obj = this.statusOpt.find((i) => i.value == status);
        return obj && obj.label;
      },
      /* 表格数据源 */
      datasource({ page, limit, where }) {
        if (where.status) {
          where.statusList = [];
          where.statusList.push(where.status);
        }
        return getList({
          pageNum: page,
          size: limit,
          ...where,
          ...this.sort
        });
      },
      async _teamPage() {
        const res = await teamPage({
          page: 1,
          size: -1,
          produceVersionId: this.current.produceVersionId
        });

        this.teamList = res.list;
      },

      getFieldModel() {
        fieldModel({ fieldModel: 't_main_category' }).then((res) => {
          const privateColumn = [
            {
              columnKey: 'action',
              label: '操作',
              width: 90,
              align: 'center',
              resizable: false,
              fixed: 'right',
              slot: 'action',
              showOverflowTooltip: true
            }
          ];

          let newRes = res.map((m) => {
            return {
              prop: 'extField.' + m.prop,
              label: m.label,
              align: 'center',
              showOverflowTooltip: true
            };
          });

          this.newColumns = [...this.columns, ...newRes, ...privateColumn];

          this.$forceUpdate();
        });
      },

      // 下达
      toRelease(row) {
        this.current = row;
        this.visible = true;
        this._teamPage();
      },
      // 下达
      confirm() {
        if (!this.releasParams.teamId) {
          return this.$message.error('请选择班组');
        }

        const loading = this.$loading({ text: '加载中...' });
        releaseWorkOrder({
          id: this.current.id,
          teamId: this.releasParams.teamId,
          singleReport: this.singleReport,
          singleReportId: this.singleReportId
        })
          .then((res) => {
            if (res) {
              this.$message.success('成功');
              this.reload();
              this.visible = false;
            }
          })
          .finally(() => {
            loading.close();
          });
      },
      /* 刷新表格 */
      reload(where) {
        this.$nextTick(() => {
          this.$refs.table.reload({ page: 1, where });
        });
      },

      onSortChange(e) {
        let sort = {
          orderBy: e.order,
          sortName: e.prop
        };
        this.sort = sort;
        this.reload();
      },

      sortTop(row) {
        row.priority = Number(row.priority) + 1;
        this.priorityChange(row);
      },
      sortBottom(row) {
        if (row.priority <= 1) {
          return;
        }
        row.priority = Number(row.priority) - 1;
        this.priorityChange(row);
      },

      priorityChange(row) {
        if (row.priority > 10) {
          row.priority = 10; // 如果大于 10，则设置为 10
        } else if (row.priority < 0) {
          row.priority = 0; // 如果小于 0，则设置为 0
        }

        this.priorityFn(row);
      },

      priorityFn: debounce(function (row) {
        let params = {
          id: row.id,
          priority: row.priority
        };
        updatePriority(params).then((res) => {});
      }, 800)
    }
  };
</script>

<style lang="scss" scoped></style>
