<template>
  <div>
    <a-form-model
      title="1d2"
      layout="vertical"
      ref="ruleForm"
      :model="form"
      :rules="rules"
      :wrapper-col="{ span: 18 }"
    >
      <div>基本信息</div>
      <a-divider></a-divider>
      <a-row>
        <a-col :span="12">
          <a-form-model-item label="真实姓名" prop="actualName">
            <a-input v-model="form.actualName" placeholder="请输入真实姓名" />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="性别" prop="sex">
            <a-select v-model="form.sex" placeholder="请选择性别">
              <a-select-option v-for="item in sexOption" :key="item.id">{{
                item.name
              }}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="身份证号" prop="idCard">
            <a-input v-model="form.idCard" placeholder="请输入身份证号" />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item ref="tel" label="手机号" prop="tel">
            <a-input
              v-model="form.tel"
              placeholder="请输入手机号"
              @blur="
                () => {
                  $refs.tel.onFieldBlur();
                }
              "
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="出生日期" prop="birthday">
            <a-date-picker v-model="form.birthday" />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="密码" prop="password">
            <a-input
              type="password"
              placeholder="不输入默认为手机号后6位"
              v-model="form.password"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="电子邮箱" prop="email">
            <a-input placeholder="请输入电子邮箱" v-model="form.email" />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="居住地址" prop="address">
            <a-input placeholder="请输入居住地址" v-model="form.address" />
          </a-form-model-item>
        </a-col>
        身份证照片
        <a-upload
          :action="`${$upload}`"
          :headers="uploadHeaders"
          list-type="picture-card"
          :file-list="fileList"
          @preview="handlePreview"
          @change="handleChange"
        >
          <div v-if="fileList.length < 2">
            <a-icon type="plus" />
            <div class="ant-upload-text">点击上传</div>
          </div>
        </a-upload>
        <span style="color: #00000073"
          >单张最多不超过4M，最多上传2张，支持JPG,PNG格式</span
        >
      </a-row>
      <div>入职信息</div>
      <a-divider></a-divider>
      <a-row>
        <a-col :span="12">
          <a-form-model-item label="岗位" prop='departmentIdPath'>
             <a-cascader
              :field-names="{
                label: 'name',
                value: 'id',
                children: 'childList',
              }"
              :options="treeData"
              placeholder="请选择"
              change-on-select
              @change="onChange"
              v-model="cascVal"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="入职时间" prop="entryDate">
            <a-date-picker
              placeholder="请选择入职时间"
              v-model="form.entryDate"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="薪资" prop="salary">
            <a-input placeholder="请输入薪资" v-model="form.salary" />
          </a-form-model-item>
        </a-col>
        <a-col :span="24">
          <div>上传资料</div>
          <a-upload
            :action="`${$baseUrl}/user/upload/uploadManageUserData`"
            :headers="uploadHeaders"
            list-type="picture"
            :default-file-list="fileList"
          >
            <a-button> <a-icon type="upload"/> 点击上传 </a-button>
          </a-upload>
          <span style="color: #00000073">支持上传PNG，JPG,PDF文件</span>
        </a-col>
      </a-row>
      <div style="margin-top: 20px">联系信息</div>
      <a-divider></a-divider>
      <a-row>
        <a-col :span="12">
          <a-form-model-item label="紧急联系人" prop="emergencyContact">
            <a-input
              placeholder="请输入紧急联系人"
              v-model="form.emergencyContact"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="紧急联系电话" prop="emergencyContactNumber">
            <a-input
              placeholder="请输入紧急联系电话"
              v-model="form.emergencyContactNumber"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="24">
          <a-form-model-item
            label="紧急联系地址"
            prop="emergencyContactAddress"
          >
            <a-input
              placeholder="请输入紧急联系地址"
              v-model="form.emergencyContactAddress"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <div  @click="u1pload">其他信息</div>
      <a-divider></a-divider>
      <a-row>
        <a-col :span="12">
          <a-form-model-item label="婚姻状态" prop="maritalStatus">
            <a-select
              placeholder="请选择婚姻状态"
              v-model="form.maritalStatus"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="民族" prop="nation">
            <a-select placeholder="请输入民族" v-model="form.nation" />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="政治面貌" prop="politicalOutlook">
            <a-select
              placeholder="请选择政治面貌"
              v-model="form.politicalOutlook"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="户口类型" prop="accountType">
            <a-select placeholder="请选择类型" v-model="form.accountType" />
          </a-form-model-item>
        </a-col>
        <a-col :span="24">
          <a-form-model-item label="备注" prop="remake">
            <a-textarea
              v-model="form.remake"
              placeholder="请输入备注"
            ></a-textarea>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
  </div>
</template>

<script>
import { insertManageUser,departmentList,uploadManageUserIdCard,manageUserInfo,EditManageUser } from "@/api/basic/department";
import store from "@/store";
function getBase64(file) {
	return new Promise((resolve, reject) => {
		const reader = new FileReader();
		reader.readAsDataURL(file);
		reader.onload = () => resolve(reader.result);
		reader.onerror = (error) => reject(error);
	});
}
export default {
	name: "Vueform",
	props: {
		type: {
			type: String,
			default:'add'
		},
		editId:Number,
	},
	watch: {
		editId: {
			handler(val) {
				if(val === null){
					return
				}
				this.form.id =val;
				manageUserInfo({id:this.form.id}).then(res=>{
					let data = res.data
					this.form.actualName = data.actualName
					this.form.sex = data.sex
					this.form.idCard = data.idCard
					this.form.tel = data.tel
					this.telephoneNum = data.tel
					// this.form.birthday = this.formatDate(data.birthday/1000,'yyyy-MM-dd hh:mm:ss')
					this.form.password = data.password
					this.form.email = data.email
					this.form.address = data.address
					this.form.idCardImgUrls = data.idCardImgUrls
					// this.form.entryDate = this.formatDate(data.entryDate/1000,'yyyy-MM-dd hh:mm:ss')
					this.form.salary = data.salary
					this.form.emergencyContact = data.emergencyContact
					this.form.emergencyContactNumber = data.emergencyContactNumber
					this.form.emergencyContactAddress = data.emergencyContactAddress
					this.form.maritalStatus = data.maritalStatus
					this.form.nation = data.nation
					this.form.politicalOutlook = data.politicalOutlook
					this.form.accountType = data.accountType
					this.form.remake = data.remake
					// 岗位
					this.cascVal = []
					let path = data.departmentIdPath.split(':')
					path.pop()
					path.splice(0,1)
					path.push(data.positionId)
					path.forEach(element => {
						this.cascVal.push(Number(element))
					});
					// 图片
				})
			},
			immediate: true,
		},
	},
	data() {
		return {
			previewVisible: false,
			previewImage: "",
			treeData:[],
			cascVal:[],
			telephoneNum:"",
			uploadHeaders: {
				"manage-login-token": store.getters.getToken,
				'Content-Type': 'multipart/form-data'
			},
			sexOption: [
				{
					id: 1,
					name: "男",
				},
				{
					id: 2,
					name: "女",
				},
				{
					id: 3,
					name: "保密",
				},
			],
			form: {
				id:null,
				actualName: "",
				sex: null,
				idCard: "",
				tel: "",
				birthday: "",
				password: "",
				email: "",
				address: "",
				idCardImgUrls: "",
				departmentId: "",
				departmentIdPath: "",
				positionId: "",
				entryDate: "",
				salary: "",
				dataImgUrls: "",
				emergencyContact: "",
				emergencyContactNumber: "",
				emergencyContactAddress: "",
				maritalStatus: "",
				nation: "",
				politicalOutlook: "",
				accountType: "",
				remake: "",
			},
			rules: {
				actualName: [
					{ required: true, message: "请输入真实姓名", trigger: "blur" },
				],
				sex: [{ required: true, message: "请选择性别", trigger: "change" }],
				idCard: [
					{ required: true, message: "请输入身份证号", trigger: "blur" },
				],
				tel: [
					{ required: true, message: "请输入手机号", trigger: "blur" },
					{ min: 11, max: 11, message: "手机号只能为11位", trigger: "blur" },
				],
				entryDate: [
					{ required: true, message: "请选择入职时间", trigger: "change" },
				],
			},
			fileList: [],
		};
	},
	created() {
		this.getData()
	},
	methods: {
		getData(){
			departmentList().then((res) => {
				this.treeData = res.data;
			});
		},
		// 提交
		submit() {
			this.$refs.ruleForm.validate((valid) => {
				if (!valid) {
					return;
				}
				if (this.type === "add") {
					insertManageUser(this.form).then((res) => {
						if(res.code===200){
							this.$message.success(res.msg)
							this.success()
							this.close()
						}
					});
				} else {
					if(this.form.tel === this.telephoneNum){
						this.form.tel = null
					}
					EditManageUser(this.form).then((res) => {
						if(res.code===200){
							this.$message.success(res.msg)
							this.success()
							this.close()
						}
					});
				}
			});
		},
		// 关闭新增员工
		close() {
			this.$refs.ruleForm.resetFields();
			this.cascVal=[]
		},
		success(){
			this.$emit('success')
		},
		async handlePreview(file) {
			if (!file.url && !file.preview) {
				file.preview = await getBase64(file.originFileObj);
			}
			this.previewImage = file.url || file.preview;
			this.previewVisible = true;
		},
		onChange(data) {
			// data [1,2,2]
			// yyyy-mm-dd hh:mm:ss
			let _data = JSON.parse(JSON.stringify(data))
			this.form.positionId = _data.pop()   //2
			this.form.departmentId = _data[_data.length-1]  //[1,2]==>2
			let str = ''
			// 1:2:
			for (let i = 0; i < _data.length; i++) {
				str += _data[i]+':'
			}
			// 0:1:2:
			this.form.departmentIdPath = '0:'+ str
		},
		handleCancel() {
			this.previewVisible = false;
		},
		handleChange({ fileList }) {
			this.fileList = fileList;
		},
		u1pload(){
			uploadManageUserIdCard().then((res) => {console.log(res);})
		}
	},
};
</script>

<style lang="less" scoped>
</style>
