<!-- 用户编辑弹窗 -->
<template>
  <el-dialog
    class="ele-dialog-form"
    :title="title"
    :visible.sync="visible"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="1000px"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-card
        shadow="never"
        header="基本信息"
        body-style="padding: 22px 22px 0 22px;"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="编码:" prop="code" style="margin-bottom: 22px">
              <el-input
                clearable
                :maxlength="20"
                v-model="form.code"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="名称:" prop="name" style="margin-bottom: 22px">
              <el-input
                clearable
                :maxlength="20"
                v-model="form.name"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>

          <el-col :span="8" style="margin-bottom: 22px">
            <el-form-item label="所属工厂:" prop="factoryId">
              <el-select
                style="width: 100%"
                clearable
                v-model="form.factoryId"
                @change="change_factoryId"
                filterable
                placeholder="请选择所属工厂"
              >
                <el-option
                  v-for="item in factoryList"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8" style="margin-bottom: 22px">
            <el-form-item label="所属厂房:" prop="workshopPlanId">
              <el-select
                v-model="form.workshopPlanId"
                @change="change_workshopPlanId"
                filterable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in workshopPlanList"
                  :key="item.id"
                  :label="item.workshopPlanName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item
              label="车间:"
              prop="workshopId"
              style="margin-bottom: 22px"
            >
              <el-select
                v-model="form.workshopId"
                @change="change_workshopId"
                multiple
                placeholder="请选择"
              >
                <el-option
                  v-for="item in options.workshopId"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="margin-bottom: 22px">
            <el-form-item label="产线:" prop="productionLineId">
              <el-select
                v-model="form.productionLineId"
                multiple
                placeholder="请选择"
              >
                <el-option
                  v-for="item in options.productionLineId"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="margin-bottom: 22px">
            <el-form-item label="工作中心:" prop="workCenterIds">
              <div class="location-warp">
                <el-select
                  v-model="form.workCenterIds"
                  multiple
                  clearable
                  filterable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in options.workCenterIds"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </div>
            </el-form-item>
          </el-col>

          <el-col :span="8" style="margin-bottom: 22px">
            <el-form-item label="生产版本:" prop="produceVersionId">
              <el-select
                v-model="form.produceVersionId"
                filterable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in versionList"
                  :key="item.id"
                  :label="item.code + '-' + item.name"
                  :value="item.id"
                  @click.native="form.produceVersionName = item.name"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8" style="margin-bottom: 22px">
            <el-form-item label="状态:" prop="">
              <el-select v-model="form.status" placeholder="" filterable>
                <el-option
                  v-for="item in statusList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-card
        shadow="never"
        header="员工配置"
        body-style="padding: 22px 22px 0 22px;"
      >
        <userTable ref="userTable" @deleteIds="deleteIds"></userTable>
      </el-card>
    </el-form>
    <template v-slot:footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="loading" @click="save">
        保存
      </el-button>
    </template>
  </el-dialog>
</template>

<script>
  import {
    listWorkshopByParentId,
    listFactoryLine,
    saveteam,
    updateteam
  } from '@/api/workforceManagement/team';
  import { pageList } from '@/api/technology/version/version.js';
  import work from '@/api/technology/work';
  import userTable from './userTable.vue';
  import { getFactoryarea } from '@/api/factoryModel';
  export default {
    components: {
      userTable
    },
    data() {
      const defaultForm = function () {
        return {
          id: '',
          code: '',
          leaderUserId: '',
          name: '',
          productionLineId: [],
          userIds: '',
          userNumber: '',
          workshopPlanId: null,
          workCenterIds: [],
          workshopId: [],
          factoryId: '',
          produceVersionId: '',
          status: 1
        };
      };
      return {
        defaultForm,
        factoryList: [],

        deleteUserIds: [],

        statusList: [
          { label: '失效', value: 0 },
          { label: '生效', value: 1 }
        ],

        // 表单数据
        form: { ...defaultForm() },
        // 表单验证规则
        rules: {
          code: [{ required: true, message: '请输入', trigger: 'blur' }],
          name: [{ required: true, message: '请输入', trigger: 'blur' }],
          factoryId: [
            { required: true, message: '请选择所属工厂', trigger: 'change' }
          ],
          workshopPlanId: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          workshopId: [
            { required: true, message: '请输入', trigger: 'change' }
          ],
          productionLineId: [
            { required: true, message: '请输入', trigger: 'change' }
          ],

          workCenterIds: [
            { required: true, message: '请选择工作中心', trigger: 'change' }
          ]
        },
        visible: false,
        type: '', // add/edit
        loading: false,
        options: {
          workshopId: [],
          productionLineId: [],
          workCenterIds: []
        },

        versionList: [],
        workshopPlanList: []
      };
    },
    computed: {
      title() {
        switch (this.type) {
          case 'add':
            return '新增班组';
            break;
          case 'edit':
            return '编辑班组';
            break;
          default:
            break;
        }
      }
    },
    created() {
      this.getFactoryList();
    },
    methods: {
      async open(type, row) {
        this.type = type;
        this.visible = true;
        this.deleteUserIds = [];

        if (type == 'edit') {
          for (const key of Object.keys(this.form)) {
            if (row[key]) {
              this.form[key] = row[key];
            }
          }

          // 人员反显
          this.$nextTick(() => {
            if (row.userVOList) {
              this.$refs.userTable.confirmStaffSelection(
                JSON.parse(JSON.stringify(row.userVOList))
              );
            }
            // 班组长
            this.$refs.userTable.setLeaderId(row.leaderUserId);
          });

          // 获取下拉列表
          await this.getlistWorkshopByParentId();
          await this.getlistCf();
          await this.getlistFactoryLineByParentId();
          await this.getlistByProductionLineId();
        }
        this.getVersionList();
      },
      deleteIds(ids) {
        this.deleteUserIds = ids || [];
      },
      /* 保存编辑 */
      save() {
        this.$refs.form.validate((valid) => {
          if (!valid) {
            return false;
          }
          this.loading = true;
          let userIds = this.$refs.userTable.datasource.map((n) => n.id);

          if (userIds.length <= 0) {
            this.$message.error('请选择员工');
            this.loading = false;
            return false;
          }

          let par = this.form;
          par.userIds = userIds;
          par.deleteUserIds = this.deleteUserIds;
          par.leaderUserId = this.$refs.userTable.getTwi();
          par.userNumber = par.userIds.length;
          if (this.type == 'add') {
            delete par.id;
          }
          const saveOrUpdate = this.type == 'add' ? saveteam : updateteam;
          saveOrUpdate(par)
            .then((msg) => {
              this.loading = false;
              this.$message.success(msg);
              this.handleClose();
              this.$emit('done');
            })
            .catch((e) => {
              this.loading = false;
              // this.$message.error(e.message);
            });
        });
      },

      // 重置表单
      restForm() {
        this.form = { ...this.defaultForm() };
        this.$nextTick(() => {
          this.$refs.form.clearValidate();
        });
      },
      handleClose() {
        this.restForm();
        this.$refs.userTable.restTable();
        this.visible = false;
        this.loading = false;
      },

      async getFactoryList() {
        const { list } = await getFactoryarea({
          pageNum: 1,
          size: 999,
          type: 1
        });
        this.factoryList = list || [];
      },

      // 获取厂房
      change_factoryId() {
        this.form.workshopPlanId = '';
        this.workshopPlanList = [];
        this.form.workshopId = '';
        this.options.workshopId = [];
        this.form.productionLineId = '';
        this.options.productionLineId = [];

        this.getlistCf();
        this.form.workCenterIds = '';
        this.options.workCenterIds = [];

        this.getlistByProductionLineId();
      },

      getlistCf() {
        let par = {
          type: 2,
          parentId: this.form.factoryId,
          size: 9999
        };
        getFactoryarea(par).then((res) => {
          this.workshopPlanList = res.list;
        });
      },

      // 获取车间
      getlistWorkshopByParentId() {
        return listWorkshopByParentId(this.form.workshopPlanId).then((res) => {
          this.options.workshopId = res.map((n) => {
            return {
              value: n.id,
              label: n.name
            };
          });
        });
      },
      // 获取产线
      getlistFactoryLineByParentId() {
        return listFactoryLine(this.form.workshopId).then((res) => {
          this.options.productionLineId = res.map((n) => {
            return {
              value: n.id,
              label: n.name
            };
          });
        });
      },
      // 获取工位
      getlistByProductionLineId() {
        return work
          .list({ pageNum: 1, size: -1, factoryId: this.form.factoryId })
          .then((res) => {
            this.options.workCenterIds = res.list.map((n) => {
              return {
                value: n.id,
                label: n.name
              };
            });
          });
      },

      change_workshopPlanId() {
        this.form.workshopId = '';
        this.options.workshopId = [];
        this.form.productionLineId = '';
        this.options.productionLineId = [];

        this.getlistWorkshopByParentId();
      },
      // 选择车间
      change_workshopId() {
        this.form.productionLineId = '';

        this.options.productionLineId = [];

        this.getlistFactoryLineByParentId();
      },

      async getVersionList() {
        const res = await pageList({
          pageNum: 1,
          size: 100
        });
        this.versionList = res.list;
      }
    }
  };
</script>
<style lang="scss" scoped>
  .location-warp {
    display: flex;

    .detail {
      margin-left: 10px;
    }
  }
</style>
