<template>
  <ele-modal
    :before-close="cancel"
    :close-on-click-modal="false"
    :maxable="true"
    :title="'批量派单'"
    :visible.sync="batchDialog"
    append-to-body
    custom-class="ele-dialog-form"
    width="1000px"
  >
    <el-form
      ref="form"
      :model="form"
      label-position="right"
      label-width="110px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="所属工作中心:" required>
            <el-select
              v-model="form.workCenterId"
              placeholder="请选择"
              style="width: 100%"
              @change="changeWork"
            >
              <el-option
                v-for="item in workCenterList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属班组:" required>
            <el-select
              v-model="form.teamId"
              placeholder="请选择"
              style="width: 100%"
              @change="changeGroups"
            >
              <el-option
                v-for="item in teamList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-form-item label="报工类型:" required>
          <el-radio-group v-model="form.singleReport">
            <el-radio :label="1">单件报工</el-radio>
            <el-radio :label="0">批量报工</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="派单方式:" required>
          <el-radio-group v-model="form.taskAss">
            <el-radio :label="1">生产订单派单</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="指派:" prop="assignType" required>
            <el-radio-group v-model="form.assignType" size="mini">
              <el-radio-button :label="1">工位</el-radio-button>
              <el-radio-button :label="2">人员</el-radio-button>
              <el-radio-button :label="3">产线</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item v-if="form.assignType == 1" label="工位:" required>
            <el-select
              v-model="form.workstationIds"
              class="ele-block"
              filterable
              multiple
              placeholder="请选择工位"
              size="mini"
            >
              <el-option
                v-for="item in stationList"
                :key="item.id"
                :label="item.name + '（' + item.code + '）'"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item v-if="form.assignType == 2" label="人员:">
            <el-select
              v-model="form.crewIds"
              class="ele-block"
              filterable
              multiple
              placeholder="请选择人员"
              size="mini"
            >
              <el-option
                v-for="item in crewList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item v-if="form.assignType == 3" label="产线:" required>
            <el-select
              v-model="form.factoryLineIds"
              class="ele-block"
              filterable
              multiple
              placeholder="请选择产线"
              size="mini"
            >
              <el-option
                v-for="item in productionList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <ele-pro-table
      ref="table"
      :columns="columns"
      :datasource="datasource"
      :needPage="false"
      row-key="userId"
    >
    </ele-pro-table>
    <div slot="footer">
      <el-button :loading="loading" plain @click="cancel">取消</el-button>
      <el-button :loading="loading" type="primary" @click="save"
        >确定
      </el-button>
    </div>
  </ele-modal>
</template>
<script>
  import {
    batchReleaseWorkOrder,
    lineByCurrentUser,
    listByFirstTaskId,
    listUserByIds,
    listWorkCenter
  } from '@/api/mainData/index.js';

  import { parameterGetByCode } from '@/api/mainData/index';

  export default {
    data() {
      return {
        batchDialog: false,
        datasource: [],
        columns: [
          {
            width: 45,
            type: 'index',
            columnKey: 'index',
            align: 'center'
          },
          {
            label: '名称',
            prop: 'productName',
            minWidth: 170
          },
          {
            label: '编码',
            prop: 'productCode',
            minWidth: 120
          },
          {
            prop: 'code',
            label: '生产订单号',
            minWidth: 210
          },
          {
            label: '计划编号',
            prop: 'productionPlanCode',
            minWidth: 150
          },
          {
            label: '批次号',
            prop: 'batchNo',
            minWidth: 100
          },
          {
            label: '要求生产数量',
            prop: 'formingNum',
            minWidth: 110
          }
        ],
        form: {
          assignType: 1,
          crewIds: '',
          workstationIds: '',
          teamId: '',
          singleReport: 0,
          workCenterId: '',
          taskAss: 1,
          factoryName: '',
          factoryLineIds: ''
        },
        workCenterList: [],
        teamList: [],
        crewList: [],
        stationList: [],
        productionList: [],
        firstTaskId: '',
        loading: false
      };
    },
    computed: {
      clientEnvironmentId() {
        return this.$store.state.user.info.clientEnvironmentId;
      }
    },
    methods: {
      cancel() {
        this.batchDialog = false;
        this.form = {
          assignType: 1,
          crewIds: '',
          workstationIds: '',
          teamId: '',
          singleReport: 0,
          workCenterId: '',
          taskAss: 1,
          factoryName: '',
          factoryLineIds: ''
        };
        this.workCenterList = [];
        this.teamList = [];
        this.crewList = [];
        this.stationList = [];
        this.productionList = [];
        this.firstTaskId = '';
        this.datasource = [];
      },
      open(list) {
        this.batchDialog = true;
        this.firstTaskId = list[0].firstTaskId;
        this.datasource = list;
        this.workCenterData();
        this.getReportType('report_type');
        // this.form.singleReport = this.clientEnvironmentId === 2 ? 0 : 1;
      },
      async workCenterData() {
        const res = await listWorkCenter(this.firstTaskId);
        this.workCenterList = res;
        if (res.length > 0) {
          this.form.factoryName = res[0].factoryName;
          this.form.workCenterId = res[0].id;
          // 查首工序
          await this.changeWork(res[0].id); // 选择工作中心
          this.getProductionData(res[0].id); // 查询产线
          this.FirstTaskIdFn(); // 查询工位数据
        } else {
          this.$message.warning(
            `${this.current.firstTaskName}工序没有工作中心,请到主数据工序管理维护工序信息!`
          );
        }
      },
      // 获取产线数据
      async getProductionData() {
        const res = await lineByCurrentUser(this.form.workCenterId);
        this.productionList = res;
      },

      async getReportType(code) {
        await parameterGetByCode({ code }).then((res) => {
          if (res) {
            this.form.singleReport =
              this.clientEnvironmentId == 2
                ? 0
                : res.value == '0'
                ? 0
                : res.value == '1'
                ? 1
                : '';
          }
        });
      },

      // 查询工位数据
      FirstTaskIdFn() {
        listByFirstTaskId(this.firstTaskId)
          .then((res) => {
            this.stationList = res;
          })
          .catch((err) => {
            this.stationList = [];
            this.$message.error(err.message);
          });
      },
      // 选择工作中心
      async changeWork(e) {
        this.form.workCenterId = e;
        // this.changeDispatch(); // 查询工序列表
        let data = this.workCenterList.find((item) => item.id == e);
        this.form.workCenterName = data.name;
        this.teamList = data.teamList || []; // 重新获取 班组数据
        if (this.teamList.length > 0) {
          this.form.teamId = this.teamList[0].id;
          await this.changeGroups(this.teamList[0].id); // 获取人员数据方法
        } else {
          // 如果没有 班组数据 将人员数据清空 并且判断
          this.crewList = [];
          this.form.teamId = '';
        }
      },
      // 选择班组 查询人员的数据
      async changeGroups(e) {
        let data = this.teamList.find((item) => item.id == e);
        this.form.teamName = data.name;
        try {
          const res = await listUserByIds([e]);
          this.crewList = res;
        } catch {
          this.crewList = [];
        }
      },
      save() {
        if (!this.form.teamId) {
          this.$message.warning('请先选择班组');
          return;
        }
        if (this.form.assignType === 1) {
          if (
            !this.form.workstationIds ||
            this.form.workstationIds.length === 0
          ) {
            this.$message.warning('请选择工位数据');
            return;
          }
        }
        if (this.form.assignType === 3) {
          if (
            !this.form.factoryLineIds ||
            this.form.factoryLineIds.length === 0
          ) {
            this.$message.warning('请选择产线数据');
            return;
          }
        }
        let data = {
          assignType: this.form.assignType,
          singleReport: this.form.singleReport,
          teamId: this.form.teamId,
          crewIds: [],
          workstationIds: [],
          factoryLineIds: []
        };
        if (this.form.assignType === 1) {
          data.workstationIds = this.form.workstationIds || [];
        } else if (this.form.assignType === 2) {
          data.crewIds = this.form.crewIds || [];
        } else {
          data.factoryLineIds = this.form.factoryLineIds || [];
        }
        let dataArr = this.datasource.map((item) => {
          return {
            id: item.id,
            ...data
          };
        });
        this.loading = true;
        batchReleaseWorkOrder(dataArr)
          .then((res) => {
            if (res) {
              this.loading = false;
              this.$message.success('操作成功');
              this.cancel();
              this.$emit('createSuccess');
            }
          })
          .catch((err) => {
            this.loading = false;
            this.$message.error(err.message);
          });
      }
    }
  };
</script>
