<!-- 用户编辑弹窗 -->
<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-row>
        <el-col :span="8">
          <el-form-item label="工厂编码:" prop="code">
            <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">
            <el-input
              clearable
              :maxlength="20"
              v-model="form.name"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="所属公司:" prop="groupId">
            <ele-tree-select
              clearable
              :data="options.groupId"
              v-model="form.groupId"
              valueKey="id"
              labelKey="name"
              placeholder="请选择"
              default-expand-all
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="状态:" prop="enabled">
            <div class="location-warp">
              <el-select
                v-model="form.enabled"
                v
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in options.zt"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div>
          </el-form-item>
        </el-col>
        <!-- options_groupId -->
        <el-col :span="8">
          <el-form-item label="负责人部门:" prop="extInfo.principalDep">
            <ele-tree-select
              clearable
              :data="options.groupId"
              v-model="form.extInfo.principalDep"
              valueKey="id"
              labelKey="name"
              placeholder="请选择"
              @change="change_principalDep"
              default-expand-all
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="负责人:" prop="leaderId">
            <el-select
              v-model="form.leaderId"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="item in options.leaderId"
                :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 label="所属区域:" prop="location_city">
            <area-select
              v-model="form.areaId"
              @checkedKeys="getAreaInfo"
              :data="areaTreeList"
              ref="tree"
            />
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="地址:" prop="location_city">
            <div class="location-warp">
              <el-cascader
                clearable
                style="width: 385px"
                v-model="form.extInfo.location"
                :options="options.cityDataLabel"
              ></el-cascader>
              <el-input
                class="detail"
                clearable
                :maxlength="20"
                v-model="form.extInfo.locationDetail"
                placeholder="请输入详细地址"
              />
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </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 {cityDataLabel} from 'ele-admin/packages/utils/regions';
import {listOrganizations} from '@/api/system/organization';
import {saveOrUpdate} from '@/api/factoryModel';
import {getUserPage} from '@/api/system/organization';
import AreaSelect from "@/views/enterpriseModel/regionalManage/components/area-cascader.vue";
import {basicAreaPageAPI} from "@/api/regionalManage";

export default {
  components: {AreaSelect},
  props: {
    options_groupId: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  watch: {
    options_groupId(nval) {
      this.toTreeData(nval);
    }
  },
  data() {
    const defaultForm = function () {
      return {
        id: '',
        code: '',
        name: '',
        groupId: '',
        areaId: '',
        areaName: '',
        extInfo: {
          principalDep: '', // 负责人部门
          location: [],
          locationDetail: ''
        },
        areaIdList: [],
        enabled: 1,
        parentId: 0,
        leaderId: '',
        type: 1 //  FACTORY(1, "工厂"), WORKSHOP_PLAN(2, "厂房"), WORKSHOP(3, "车间"), LINE(4, "厂线");
      };
    };
    return {
      defaultForm,
      // 表单数据
      form: {...defaultForm()},
      // 表单验证规则
      rules: {
        code: [{required: true, message: '请输入', trigger: 'blur'}],
        name: [{required: true, message: '请输入', trigger: 'blur'}],
        groupId: [{required: true, message: '请输入', trigger: 'blur'}],
        leaderId: {
          required: true,
          message: '请输入',
          trigger: 'change'
        },
        'extInfo.principalDep': [
          {required: true, message: '请输入', trigger: 'change'}
        ]
      },
      visible: false,
      areaList: [],
      areaTreeList: [],
      type: '', // add/edit
      loading: false,
      options: {
        zt: [
          {
            label: '生效',
            value: 1
          },
          {
            label: '未生效',
            value: 0
          }
        ],
        groupId: [],
        cityDataLabel,
        leaderId: []
      }
    };
  },
  computed: {
    title() {
      switch (this.type) {
        case 'add':
          return '新增工厂';
          break;
        case 'edit':
          return '编辑工厂';
          break;
        default:
          break;
      }
    }
  },
  created() {
    this.getGs();
    this.getBasicAreaList();
  },
  methods: {
    open(type, row) {
      this.type = type;
      this.visible = true;
      if (type == 'edit') {
        for (const key of Object.keys(this.form)) {
          if (key !== 'extInfo') {
            this.form[key] = row[key];
          } else {
            for (const el of Object.keys(this.form.extInfo)) {
              this.form.extInfo[el] = row.extInfo[el];
            }
          }
        }

        this.getUserPage();
      }
    },
    toTreeData(val) {
      this.options.principalDep = this.$util.toTreeData({
        data: val,
        idField: 'id',
        parentIdField: 'parentId'
      });
    },
    /* 保存编辑 */
    save() {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return false;
        }
        this.loading = true;

        if (this.type == 'add') {
          delete this.form.id;
        }
        saveOrUpdate(this.form)
          .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.visible = false;
    },
    /* 获取区域集合 */
    async getBasicAreaList() {
      this.areaList = await basicAreaPageAPI(
        {
          pageNum: 1,
          size: 9999
        }
      )
      this.areaTreeList = this.$util.toTreeData({
        data: this.areaList,
        idField: 'id',
        parentIdField: 'parentId'
      });

    },
    getAreaInfo(nodeInfo) {
      this.form.areaName = nodeInfo[0]?.pathLabels.join('/') || ''
      this.form.areaId = this.form.areaId || ''
    },
    // 获取公司数据
    getGs() {
      listOrganizations().then((list) => {
        this.options.groupId = this.$util.toTreeData({
          data: list,
          idField: 'id',
          parentIdField: 'parentId'
        });
      });
    },
    // 选择负责人部门
    change_principalDep() {
      this.form.leaderId = '';
      this.getUserPage();
    },
    // 获取人员
    getUserPage() {
      if (!this.form.extInfo.principalDep) return this.options.leaderId = []
      let par = {
        groupId: this.form.extInfo.principalDep,
        size: 999
      };
      getUserPage(par).then((res) => {
        this.options.leaderId = res.list;
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.location-warp {
  display: flex;

  .detail {
    margin-left: 10px;
  }
}

:deep(
    .el-dialog:not(.ele-dialog-form)
      .el-dialog__body
      .el-form
      .el-form-item:last-child
  ) {
  margin-bottom: 22px;
}
</style>
