<template>
  <ele-modal
    custom-class="ele-dialog-form long-dialog-form"
    :centered="true"
    v-if="visible"
    :visible.sync="visible"
    title="指派"
    width="30%"
    :close-on-click-modal="false"
    :append-to-body="true"
    @close="cancel"
  >
    <el-form
      label-width="100px"
      ref="form"
      :model="form"
      :rules="rules"
      style="margin-top: 30px"
    >
      <el-form-item label="分管部门" prop="fgDeptId" style="margin-bottom: 22px">
        <ele-tree-select
          clearable
          :data="groupTreeData"
          v-model="form.fgDeptId"
          valueKey="id"
          labelKey="name"
          placeholder="请选择"
          @change="change_principalDep"
          default-expand-all
        />
      </el-form-item>

      <el-form-item label="业务员" prop="salesmanId">
        <personSelect
          ref="directorRef"
          v-model="form.salesmanId"
          @selfChange="salesmanChange"
          :init="false"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="footer">
      <el-button type="primary" @click="save">保存</el-button>
      <el-button @click="cancel">返回</el-button>
    </div>
  </ele-modal>
</template>

<script>
  import {assign} from '@/api/saleManage/contact';

  import dictMixins from '@/mixins/dictMixins';
  import personSelect from '@/components/CommomSelect/person-select.vue';
  import { listOrganizations } from '@/api/system/organization';
  import { copyObj } from '@/utils/util';

  import parentList from './parentList.vue';
  let formDef = {
    contactIds: [],
    contactNames: [],
    fgDeptId: '',
    fgDeptName: '',
    salesmanId: '',
    salesmanName: ''
  };
  export default {
    mixins: [dictMixins],
    components: {
      personSelect
    },

    data() {
      return {
        visible: false,

        form: copyObj(formDef),

        rules: {
          fgDeptId: [{ required: true, message: '分管部门', trigger: 'change' }],
          salesmanId: [{ required: true, message: '业务员', trigger: 'blur' }]
        },

        // 提交状态
        loading: false,

        // 组织机构树形结构数据
        groupTreeData: [],
        // 组织机构平铺数据
        groupData: []
      };
    },
    created() {
      this.getGroupAll();
    },
    methods: {
      async open(contactIds, contactNames) {
        this.form.contactNames = contactNames.toString()
        this.form.contactIds = contactIds.toString()
        this.visible = true;
      },

      // 获取公司数据
      getGroupAll() {
        listOrganizations().then((list) => {
          this.groupData = list;
          this.groupTreeData = this.$util.toTreeData({
            data: list,
            idField: 'id',
            parentIdField: 'parentId'
          });
        });
      },

      // 选择负责人部门
      change_principalDep(id) {
        const info = this.groupData.find((e) => e.id == id);
        this.form.fgDeptName = info.name;
        this.form.salesmanId = '';
        this.form.salesmanName = '';
        // 根据部门获取人员
        const params = { groupId: id };
        this.$nextTick(() => {
          this.$refs.directorRef.getList(params);
        });
      },
      salesmanChange(val, info) {
        this.form.salesmanName = info.name;
      },

      getValidate() {
        return Promise.all([
          new Promise((resolve, reject) => {
            this.$refs.form.validate((valid) => {
              if (!valid) {
                this.activeName = 'base';
                reject(false);
              } else {
                resolve(true);
              }
            });
          })
        ]);
      },
      async save() {
        try {
          await this.getValidate();
          // 表单验证通过，执行保存操作
          this.loading = true;

          assign(this.form)
            .then((res) => {
              this.loading = false;
              this.$message.success('指派成功');
              this.$emit('done');
              this.cancel();
            })
            .catch((e) => {
              //this.loading = false;
            });
        } catch (error) {
          // 表单验证未通过，不执行保存操作
        }
      },
      cancel() {
        this.$nextTick(() => {
          this.form = copyObj(formDef)
          this.visible = false;
        });
      },

    }
  };
</script>
