<template>
  <a-form-model :model="form" :rules="rules" class="yo-form" ref="form">
    <a-spin :spinning="loading">
      <a-icon slot="indicator" spin type="loading" />
      <a-row :gutter="16">
        <a-col :span="10">
          <h3>基本信息</h3>
          <div class="yo-form-group">
            <a-form-model-item label="账号" prop="account">
              <a-input placeholder="请输入账号" v-model="form.account" />
            </a-form-model-item>
            <a-form-model-item label="姓名" prop="name">
              <a-input placeholder="请输入姓名" v-model="form.name" />
            </a-form-model-item>
            <template v-if="mode == 'add'">
              <a-form-model-item label="密码" prop="password">
                <a-input-password placeholder="请输入密码" v-model="form.password" />
              </a-form-model-item>
              <a-form-model-item label="确认密码" prop="confirm">
                <a-input-password placeholder="请确认密码" v-model="form.confirm" />
              </a-form-model-item>
            </template>
            <a-form-model-item label="昵称">
              <a-input placeholder="请输入昵称" v-model="form.nickName" />
            </a-form-model-item>
            <a-form-model-item label="生日">
              <a-date-picker
                @change="(date) => form.birthday = date ? moment(date).format('YYYY-MM-DD') : undefined"
                class="w-100-p"
                placeholder="请选择生日"
                v-model="form.birthday"
              />
            </a-form-model-item>
            <a-form-model-item label="性别" prop="sex">
              <a-radio-group v-model="form.sex">
                <a-radio-button :value="1">
                  <a-icon :style="{ color: '#1890ff' }" type="man" />男
                </a-radio-button>
                <a-radio-button :value="2">
                  <a-icon :style="{ color: '#eb2f96' }" type="woman" />女
                </a-radio-button>
              </a-radio-group>
            </a-form-model-item>
            <a-form-model-item label="邮箱" prop="email">
              <a-input placeholder="请输入邮箱" v-model="form.email" />
            </a-form-model-item>
            <a-form-model-item label="手机号" prop="phone">
              <a-input placeholder="请输入手机号" v-model="form.phone" />
            </a-form-model-item>
            <a-form-model-item label="电话" prop="tel">
              <a-input placeholder="请输入电话" v-model="form.tel" />
            </a-form-model-item>
          </div>
        </a-col>
        <a-col :span="14">
          <h3>员工信息</h3>
          <div class="yo-form-group">
            <a-form-model-item label="所属组织机构" prop="sysEmpParam.orgId">
              <a-tree-select
                :tree-data="orgData"
                placeholder="请选择所属组织机构"
                treeDefaultExpandAll
                v-model="form.sysEmpParam.orgId"
              />
            </a-form-model-item>
            <a-form-model-item label="工号">
              <a-input placeholder="请输入工号" v-model="form.sysEmpParam.jobNum" />
            </a-form-model-item>
            <a-form-model-item label="职位信息" prop="sysEmpParam.posIdList">
              <a-select mode="multiple" placeholder="请选择职位信息" v-model="form.sysEmpParam.posIdList">
                <a-select-option
                  :key="i"
                  :value="item.id"
                  v-for="(item, i) in posData"
                >{{ item.name }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </div>
          <h4>附加信息</h4>
          <a-table
            :columns="extColumns"
            :data-source="form.sysEmpParam.extIds"
            :pagination="false"
            size="small"
          >
            <template slot="footer">
              <a-button @click="onAddExtData" block icon="plus" type="dashed">新增一项</a-button>
            </template>
            <template slot="orgId" slot-scope="text, record">
              <a-tree-select
                :default-value="text"
                :tree-data="orgData"
                @change="value => onChangeExtData(value, record, 'orgId')"
                placeholder="请选择附加组织机构"
                tree-default-expand-all
              />
            </template>
            <template slot="posId" slot-scope="text, record">
              <a-select
                :default-value="text"
                @change="value => onChangeExtData(value, record, 'posId')"
                placeholder="请选择附加职位信息"
              >
                <a-select-option
                  :key="i"
                  :value="item.id"
                  v-for="(item, i) in posData"
                >{{ item.name }}</a-select-option>
              </a-select>
            </template>
            <template slot="action" slot-scope="text, record">
              <a-button @click="onRemoveExtData(record)" size="small" type="danger">删除</a-button>
            </template>
          </a-table>
        </a-col>
      </a-row>
    </a-spin>
  </a-form-model>
</template>
<script>
import moment from 'moment';

const validateToNextPassword = (rule, value, callback) => {
  callback();
};
const compareToFirstPassword = (rule, value, callback) => {
  callback();
};

export default {
  props: ['mode'],

  data() {
    return {
      form: {
        sysEmpParam: {},
      },
      rules: {
        account: [{ required: true, min: 5, message: '请输入至少五个字符的账号' }],
        name: [{ required: true, message: '请输入姓名' }],
        password: [
          { required: true, min: 5, message: '请输入至少五个字符的密码' },
          { validator: validateToNextPassword },
        ],
        confirm: [{ required: true, message: '请确认密码' }, { validator: compareToFirstPassword }],
        sex: [{ required: true, message: '请选择性别' }],
        phone: [{ required: true, message: '请输入手机号' }],
        'sysEmpParam.orgId': [{ required: true, message: '请选择所属组织机构' }],
        'sysEmpParam.posIdList': [{ required: true, message: '请选择职位信息' }],
      },

      loading: false,

      orgData: [],
      posData: [],

      extColumns: [
        {
          title: '附属机构',
          dataIndex: 'orgId',
          width: '45%',
          scopedSlots: { customRender: 'orgId' },
        },
        {
          title: '附属岗位',
          dataIndex: 'posId',
          width: '45%',
          scopedSlots: { customRender: 'posId' },
        },
        {
          title: '操作',
          key: 'action',
          width: '70px',
          scopedSlots: { customRender: 'action' },
        },
      ],
    };
  },
  methods: {
    moment,

    /**
     * 必要的方法
     * 在打开编辑页时允许填充数据
     */
    onFillData(record) {
      const form = this.$_.cloneDeep(record);
      // 日期特殊处理
      if (form.birthday) {
        form.birthday = moment(form.birthday).format('YYYY-MM-DD');
      }
      // 提交的时候是"param",而获取下来却是"info",在这里转换一下
      if (form.sysEmpInfo) {
        form.sysEmpParam = form.sysEmpInfo;
        delete form.sysEmpInfo;
      } else if (!form.sysEmpParam) {
        form.sysEmpParam = {
          extIds: [],
        };
      }
      // 转换职位信息列表
      if (form.sysEmpParam.positions) {
        form.sysEmpParam.posIdList = form.sysEmpParam.positions.map((p) => p.posId);
      }
      // 附加信息
      if (form.sysEmpParam.extOrgPos) {
        form.sysEmpParam.extIds = form.sysEmpParam.extOrgPos.map((p, i) => {
          return {
            key: i,
            orgId: p.orgId,
            posId: p.posId,
          };
        });
      }
      this.form = form;
    },

    /**
     * 必要的方法
     * 在外部窗口进行保存时调用表单验证
     */
    onValidate(callback) {
      this.$refs.form.validate(callback);
    },

    /**
     * 必要的方法
     * 在外部窗口关闭或重置时对表单验证进行初始化
     */
    onResetFields() {
      setTimeout(() => {
        this.form = {
          sysEmpParam: {},
        };
        this.$refs.form.resetFields();
      }, 300);
    },

    async onInit() {
      this.loading = true;
      this.orgData = await this.onLoadOrgData();
      this.posData = await this.onLoadPosData();
      this.loading = false;
    },

    onLoadOrgData() {
      return this.$api.getOrgTree().then(({ data }) => {
        return data;
      });
    },

    onLoadPosData() {
      return this.$api.sysPosList().then(({ data }) => {
        return data;
      });
    },

    onAddExtData() {
      this.form.sysEmpParam.extIds.push({
        key: this.form.sysEmpParam.extIds.length,
        orgId: undefined,
        posId: undefined,
      });
    },

    onRemoveExtData(record) {
      const ext = this.form.sysEmpParam.extIds,
        remove = ext.find((p) => p.key === record.key),
        index = ext.indexOf(remove);

      ext.splice(index, 1);
    },

    onChangeExtData(value, record, type) {
      record[type] = value;
    },
  },
};
</script>