<!-- 用户编辑弹窗 -->
<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">
            <el-form-item
              label="车间:"
              prop="workshopId"
              style="margin-bottom: 22px"
            >
              <el-select
                v-model="form.workshopId"
                @change="change_workshopId"
                placeholder="请选择"
                style="width: 100%"
              >
                <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"
                @change="change_productionLineId"
                placeholder="请选择"
                style="width: 100%"
              >
                <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="workStationIds">
              <div class="location-warp">
                <el-select
                  v-model="form.workStationIds"
                  multiple
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in options.workStationIds"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-card
        shadow="never"
        header="员工配置"
        body-style="padding: 22px 22px 0 22px;"
      >
        <userTable ref="userTable"></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,
  listFactoryLineByParentId,
  listByProductionLineId,
  saveteam,
  updateteam
} from '@/api/workforceManagement/team';
import userTable from './userTable.vue';
export default {
  components: {
    userTable
  },
  data() {
    const defaultForm = function () {
      return {
        id: '',
        code: '',
        leaderUserId: '',
        name: '',
        productionLineId: '',
        userIds: '',
        userNumber: '',
        workStationIds: [],
        workshopId: ''
      };
    };
    return {
      defaultForm,
      // 表单数据
      form: { ...defaultForm() },
      // 表单验证规则
      rules: {
        code: [{ required: true, message: '请输入', trigger: 'blur' }],
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        workshopId: [{ required: true, message: '请输入', trigger: 'change' }],
        productionLineId: [
          { required: true, message: '请输入', trigger: 'change' }
        ]
      },
      visible: false,
      type: '', // add/edit
      loading: false,
      options: {
        workshopId: [],
        productionLineId: [],
        workStationIds: []
      }
    };
  },
  computed: {
    title() {
      switch (this.type) {
        case 'add':
          return '新增班组';
          break;
        case 'edit':
          return '编辑班组';
          break;
        default:
          break;
      }
    }
  },
  created() {
    this.getlistWorkshopByParentId();
  },
  methods: {
    async open(type, row) {
      this.type = type;
      this.visible = true;
      if (type == 'edit') {
        for (const key of Object.keys(this.form)) {
          if (row[key]) {
            this.form[key] = row[key];
          }
        }
        // 工位反显
        if (row.workStationList.length > 0) {
          this.form.workStationIds = row.workStationList.map(
            (n) => n.workstationId
          );
        }
        // 人员反显
        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.getlistFactoryLineByParentId();
        this.getlistByProductionLineId();
      }
    },
    /* 保存编辑 */
    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.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;
    },
    // 获取车间
    getlistWorkshopByParentId() {
      let par = this.$store.state.user.info.factoryId;
      return listWorkshopByParentId(par).then((res) => {
        this.options.workshopId = res.map((n) => {
          return {
            value: n.id,
            label: n.name
          };
        });
      });
    },
    // 获取产线
    getlistFactoryLineByParentId() {
      let par = this.form.workshopId;
      return listFactoryLineByParentId(par).then((res) => {
        this.options.productionLineId = res.map((n) => {
          return {
            value: n.id,
            label: n.name
          };
        });
      });
    },
    // 获取工位
    getlistByProductionLineId() {
      let par = this.form.productionLineId;
      return listByProductionLineId(par).then((res) => {
        this.options.workStationIds = res.map((n) => {
          return {
            value: n.id,
            label: n.name
          };
        });
      });
    },
    // 选择车间
    change_workshopId() {
      this.form.productionLineId = '';
      this.form.workStationIds = [];
      this.options.productionLineId = [];
      this.options.workStationIds = [];
      this.getlistFactoryLineByParentId();
    },
    // 选择产线
    change_productionLineId() {
      this.form.workStationIds = [];
      this.options.workStationIds = [];
      this.getlistByProductionLineId();
    }
  }
};
</script>
<style lang="scss" scoped>
.location-warp {
  display: flex;
  .detail {
    margin-left: 10px;
  }
}
</style>
