<template>
  <ele-modal
    :width="modelWidth"
    :visible.sync="dispatchVisible"
    :close-on-click-modal="false"
    custom-class="ele-dialog-form"
    :maxable="true"
    :title="'派单'"
    append-to-body
    :before-close="cancel"
  >
    <div class="form-wrapper">
      <el-form
        ref="form"
        :model="form"
        :inline="true"
        label-position="right"
        label-width="100px"
      >
        <el-row :gutter="10" class="basic" type="flex" style="flex-wrap: wrap">
          <el-col
            :xs="12"
            :sm="12"
            :md="12"
            :lg="8"
            :xl="6"
            v-for="item in fieldList"
            :key="item.prop"
          >
            <el-form-item :label="item.label">
              <el-date-picker
                class="w100"
                v-model="current[item.prop]"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                v-if="item.type == 'date'"
                placeholder=" "
              ></el-date-picker>
              <el-input :value="fieldValue(item.prop)" disabled v-else />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
            <el-form-item label="所属工厂:">
              <el-input v-model="form.factoryName" :disabled="true"> </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
            <el-form-item label="所属工作中心:">
              <el-select
                style="width: 100%"
                v-model="form.workCenterId"
                placeholder="请选择"
                @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 :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
            <el-form-item label="所属班组:" required>
              <el-select
                style="width: 100%"
                v-model="form.teamId"
                placeholder="请选择"
                @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">
              <!-- v-if="clientEnvironmentId != 2" -->
              <el-radio :label="1" :disabled="singleDis">单件报工</el-radio>
              <el-radio :label="0" :disabled="batchDis">批量报工</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="派单方式:" prop="taskAss">
            <!-- @change="changeDispatch" -->
            <el-radio-group v-model="form.taskAss">
              <el-radio :label="1" :disabled="orderDis">生产订单派单</el-radio>
              <el-radio :label="0" :disabled="procTaskDis"
                >工序任务派单</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-row>
        <el-row v-if="form.taskAss == 1">
          <el-col :span="24">
            <el-form-item label="指派:" prop="assignType">
              <el-radio-group
                v-model="form.assignType"
                size="mini"
                @change="assignRadio"
              >
                <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-form-item required label="工位:" v-if="form.assignType == 1">
            <el-select
              class="ele-block"
              v-model="form.workstationIds"
              placeholder="请选择工位"
              size="mini"
              multiple
              filterable
            >
              <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-form-item label="人员:" v-if="form.assignType == 2">
            <el-select
              class="ele-block"
              v-model="form.crewIds"
              placeholder="请选择人员"
              size="mini"
              filterable
              multiple
            >
              <el-option
                v-for="item in crewList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="产线:" v-if="form.assignType == 3" required>
            <el-select
              class="ele-block"
              v-model="form.factoryLineIds"
              placeholder="请选择产线"
              size="mini"
              filterable
              multiple
            >
              <el-option
                v-for="item in productionList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>

        <el-tabs
          class="process_list"
          v-model="processId"
          type="border-card"
          @tab-click="handleClick"
          v-show="form.taskAss == 0"
          v-loading="tabsLoading"
        >
          <el-tab-pane
            v-for="(item, index) in processList"
            :key="item.id"
            :label="item.name"
            :name="item.id"
          >
            <span style="color: green">
              工序编码：{{ item.code }}，所属工作中心：{{
                item.workCenterName
              }}</span
            >
            <ele-pro-table
              class="table"
              :ref="`tableRef${index}`"
              :columns="columns(item)"
              :datasource="item.list"
              cache-key="systemRoleTable"
              :pageSize="20"
              v-loading="tabLoading"
              :selection.sync="item.selection"
              row-key="id"
            >
              <template v-slot:toolbar>
                <el-button
                  type="primary"
                  @click="dispatch(item, 1)"
                  :loading="toolbarLoading"
                  :disabled="!item.isDisable"
                >
                  派单
                </el-button>
                <el-button
                  type="primary"
                  @click="dispatch(item, 2)"
                  :loading="toolbarLoading"
                  :disabled="!item.isDisable"
                >
                  撤回
                </el-button>
                <el-button
                  type="primary"
                  @click="dispatch(item, 3)"
                  :loading="toolbarLoading"
                  :disabled="!item.isDisable"
                >
                  保存
                </el-button>

                <div style="margin-left: 50px; display: inline-block">
                  <span
                    class="text"
                    style="
                      font-weight: bold;
                      font-size: 14px;
                      margin-right: 8px;
                    "
                    >指派:</span
                  >
                  <el-radio-group
                    v-model="item.assignType"
                    size="mini"
                    @change="(e) => changeRadio(e, index)"
                  >
                    <el-radio-button
                      :label="1"
                      :disabled="radioBun(item, 'stationDis')"
                      >工位</el-radio-button
                    >
                    <el-radio-button
                      :label="2"
                      :disabled="radioBun(item, 'staffDis')"
                      >人员</el-radio-button
                    >
                    <el-radio-button
                      :label="3"
                      :disabled="radioBun(item, 'lineDis')"
                      >产线</el-radio-button
                    >
                  </el-radio-group>
                </div>

                <div
                  style="margin-left: 50px; display: inline-block"
                  v-if="timeSlot(item)"
                >
                  时间段: {{ item.startDate }} ----- {{ item.endDate }}
                </div>
              </template>
              <template v-slot:quantity="{ row }">
                <el-input
                  :disabled="permissions(row)"
                  type="number"
                  v-model="row.quantity"
                  placeholder="请输入数量"
                  @input="(e) => handleQuantityInput(e, row, item)"
                ></el-input>
              </template>
              <template v-slot:weight="{ row }">
                <el-input
                  :disabled="permissions(row)"
                  type="number"
                  v-model="row.weight"
                  placeholder="请输入重量"
                  @input="(e) => handleWeightInput(e, row, item)"
                ></el-input>
              </template>
              <template v-slot:teamTimeIds="{ row }">
                <el-select
                  :disabled="permissions(row)"
                  multiple
                  v-model="row.teamTimeIds"
                  placeholder="班次"
                  @change="(e) => shiftSelection(e, row, item)"
                >
                  <el-option
                    v-for="item in shiftList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </template>
              <template v-slot:startTime="{ row }">
                <el-date-picker
                  :disabled="permissions(row)"
                  class="w100"
                  v-model="row.startTime"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="开始时间"
                  @change="handleStartTimeChange(row, item)"
                ></el-date-picker>
              </template>
              <template v-slot:endTime="{ row }">
                <el-date-picker
                  :disabled="permissions(row)"
                  class="w100"
                  v-model="row.endTime"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  @change="handleEndTimeChange(row, item)"
                  placeholder="完成时间"
                ></el-date-picker>
              </template>

              <template v-slot:action="{ row }">
                <!--  :disabled="resetBtnDis(row)" -->
                <el-popconfirm
                  title="确定要重置该条数据吗？"
                  @confirm="resetData(row, item)"
                  v-if="resetBtnDis(row)"
                >
                  <template v-slot:reference>
                    <el-link type="primary" :underline="false"> 重置 </el-link>
                  </template>
                </el-popconfirm>
              </template>
            </ele-pro-table>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </div>

    <div slot="footer">
      <el-button plain @click="cancel">取消</el-button>
      <el-button type="primary" @click="confirm" :loading="toolbarLoading"
        >确定</el-button
      >
    </div>
  </ele-modal>
</template>

<script>
  import releaseMixin from '../mixins/release';
  import { parameterGetByCode } from '@/api/mainData/index';
  export default {
    components: {},
    props: {
      current: {
        type: Object,
        default: () => {}
      },
      dispatchVisible: {
        type: Boolean,
        default: false
      }
    },
    mixins: [releaseMixin],
    data() {
      return {
        processId: '',
        tabLoading: false,
        dynamicName: '工位名称',
        form: {
          assignType: '',
          crewIds: '',
          workstationIds: '',
          teamId: '',
          singleReport: '',
          workCenterId: '',
          taskAss: '',
          factoryName: '',
          factoryLineIds: ''
        },
        toolbarLoading: false,
        processList: [],
        workCenterList: [],
        teamList: [],
        tabsLoading: false,
        stationList: [], // 工位的数据
        productionList: [], // 产线的数据
        crewList: [], // 人员的数据
        procTaskDis: false, // 工序任务派单选择
        firstTaskindex: '', // 首工序id 对应的工序列表数据下标
        fieldList: [
          { label: '生产订单号:', prop: 'code' },
          { label: '计划编号:', prop: 'productionPlanCode' },
          { label: '工艺路线:', prop: 'produceRoutingName' },
          // { label: '编码', prop: 'productCode' },
          { label: '名称:', prop: 'productName' },
          { label: '生产编号:', prop: 'productionCodes' },
          { label: '牌号:', prop: 'brandNo' },
          { label: '批次号:', prop: 'batchNo' },
          { label: '型号:', prop: 'model' },
          { label: '要求生产数量:', prop: 'formingNum' },
          { label: '要求生产重量:', prop: 'initialWeight' },
          { label: '计划开始时间:', prop: 'planStartTime', type: 'date' },
          { label: '计划结束时间:', prop: 'planCompleteTime', type: 'date' }
        ],
        shiftList: [],
        dateValue: '',
        orderDis: false, // 生产订单派单
        singleDis: false, // 单个报工
        batchDis: false, // 批量报工
        isDispatchRow: {}, // 查询是否派单数据
        time_calc_code: '0' // 是否进行时间赋值 0 否 1 是
      };
    },
    computed: {
      fieldValue() {
        return (field) => {
          return this.current[field];
        };
      },
      clientEnvironmentId() {
        return this.$store.state.user.info.clientEnvironmentId;
      },
      userInfo() {
        return this.$store.state.user.info;
      },
      modelWidth() {
        // if(this.form.taskAss == 1){
        //   return '1000px'
        // }
        return '75vw';
      },
      // 重置按钮 的置灰权限 没有进行操作跟派单的数据 置灰
      resetBtnDis() {
        return (row) => {
          if (!row.status) return false;
          let flag = row.status.code != 1;
          return flag;
        };
      },
      // 指派单选框操作 已派单的 其它两个按钮不能操作
      radioBun() {
        return (row, type) => {
          if (!row.radioBun) return false;
          let flag = row.radioBun[type];
          return flag;
        };
      },
      // 列表输入框操作 已派单的不能操作
      permissions() {
        return (row) => {
          if (!row.status) return false;
          if (row.status.code == 1) return true;
        };
      },
      // 时间段显示
      timeSlot() {
        return (item) => {
          if (!item.startDate || !item.endDate) {
            return false;
          }
          return true;
        };
      },
      columns() {
        return (val) => {
          let data =
            val.assignType == 1
              ? [
                  {
                    prop: 'assetCode',
                    label: '设备编码',
                    align: 'center',
                    width: 150
                  },
                  {
                    prop: 'assetName',
                    label: '设备名称',
                    align: 'center',
                    width: 150
                  },
                  {
                    prop: 'assetModelType',
                    label: '设备型号',
                    align: 'center',
                    width: 150
                  },
                  {
                    prop: 'assetCategoryLevelPath',
                    label: '设备类型',
                    align: 'center',
                    width: 150
                  }
                ]
              : [];

          return [
            {
              columnKey: 'index',
              label: '序号',
              type: 'index',
              width: 55,
              align: 'center',
              fixed: 'left'
            },
            {
              width: 45,
              type: 'selection',
              columnKey: 'selection',
              align: 'center',
              fixed: 'left',
              reserveSelection: true
            },
            {
              prop: 'name',
              label: this.dynamicName,
              align: 'center',
              width: 200
            },
            {
              prop: 'code',
              label: '编码',
              align: 'center',
              width: 200
            },
            ...data,

            {
              prop: 'status',
              label: '状态',
              align: 'center',
              width: 150,
              formatter: (row) => {
                if (!row.status) return '';
                return row.status.desc || '';
              }
            },
            {
              slot: 'quantity',
              prop: 'quantity',
              label: '数量',
              align: 'center',
              width: 140
            },
            {
              slot: 'weight',
              prop: 'weight',
              label: `重量(${this.current.newWeightUnit})`,
              align: 'center',
              width: 140
            },
            {
              slot: 'teamTimeIds',
              prop: 'teamTimeIds',
              label: '班次',
              align: 'center',
              minWidth: 220
            },
            {
              slot: 'startTime',
              prop: 'startTime',
              label: '计划开始时间',
              align: 'center',
              minWidth: 240
            },
            {
              slot: 'endTime',
              prop: 'endTime',
              label: '计划完成时间',
              align: 'center',
              minWidth: 240
            },
            {
              columnKey: 'action',
              label: '操作',
              width: 120,
              align: 'center',
              resizable: false,
              fixed: 'right',
              slot: 'action'
            }
          ];
        };
      }
    },
    watch: {},
    created() {
      this.getDispatchMethod('dispatch_method');
      this.getAssignmentMethod('assignment_method');
      this.getReportType('report_type');
      // 时间计算规则code
      this.getCode();
      this.workCenterData(); // 查询工作中心
      this.getClassesData(); // 查询班次
      this.queryCheckExists(); // 查询是否派单
      // this.form.singleReport = this.clientEnvironmentId == 2 ? 0 : '';
      this.dateValue = this.getFormattedDate();
    },
    methods: {
      getCode() {
        parameterGetByCode({
          code: 'time_calculation_rules'
        }).then((res) => {
          if (res) {
            this.time_calc_code = res.value || '0';
          }
        });
      },

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

      async getDispatchMethod(code) {
        await parameterGetByCode({ code }).then((res) => {
          if (res) {
            this.form.taskAss = res.value == '0' ? 0 : 1;
            console.log(this.form.taskAss, 'this.form.taskAss');
          }
        });
      },

      async getAssignmentMethod(code) {
        await parameterGetByCode({ code }).then((res) => {
          if (res) {
            this.form.assignType =
              res.value == '0' ? 1 : res.value == '1' ? 2 : 3;
          }
        });
      }
    }
  };
</script>

<style lang="scss" scoped>
  .top-box {
    display: flex;
    margin-bottom: 10px;
    .item-box {
      flex: 1;
    }
  }

  .radio-box {
    margin: 10px 0;
  }

  .table {
    margin-top: 20px;
  }

  ::v-deep .el-radio-button__orig-radio:checked + .el-radio-button__inner {
    background-color: #10d070;
    border-color: #10d070;
  }
  ::v-deep .el-radio-button__orig-radio:checked + .el-radio-button__inner {
    box-shadow: none;
  }

  // ::v-deep .ele-block{
  //   width: 240px;
  // }

  // ::v-deep .basic {
  //   .el-form-item {
  //     width: 100%;
  //   }

  //   .form80 {
  //     .el-form-item__content {
  //       width: calc(100% - 80px);
  //     }
  //   }

  //   .form65 {
  //     .el-form-item__content {
  //       width: calc(100% - 65px);
  //     }
  //   }

  //   .el-form-item__label {
  //     padding: 0 4px 0 0;
  //   }

  //   .item_label {
  //     white-space: nowrap;
  //     overflow: hidden;
  //     text-overflow: ellipsis;
  //     width: 100%;
  //   }
  // }
</style>
