<template>
    <div class="addStaff">
        <div class="secendPage">
            <ul>
                <li class="titleLi">
                    <span class="required">*</span>
                    企业名称：
                    <input
                        type="text"
                        placeholder="带出不可改"
                        readonly
                        v-model="newWorker.qymc"
                    />
                </li>
                <li class="titleLi">
                    <span class="required">*</span>
                    姓名：
                    <input
                        type="text"
                        placeholder="请填写"
                        v-model="newWorker.xm"
                    />
                </li>
                <li class="titleLi">
                    <span class="required">*</span>
                    性别：
                    <van-dropdown-menu>
                        <van-dropdown-item
                            v-model="newWorker.xb"
                            :options="option2"
                        />
                    </van-dropdown-menu>
                </li>
                <li class="titleLi">
                    <span class="required">*</span>
                    手机号：
                    <input
                        type="text"
                        placeholder="请填写"
                        v-model="newWorker.sjhm"
                    />
                </li>
                <li class="titleLi titleLiLast">
                    <span class="required">*</span>
                    门禁类型：
                </li>
                <li class="titleLi titleLiUploader">
                    <van-checkbox-group v-model="result" @change="cjmjType">
                        <!-- <div class="mjTypeBox">
                            <van-checkbox name="1" shape="square"
                                ><div class="mjType">身份证：</div>
                            </van-checkbox>
                            <input
                                type="text"
                                placeholder="输入身份证号"
                                :disabled="!readOnly"
                                v-model="newWorker.sfzmhm"
                            />
                        </div> -->
                        <van-checkbox
name="2"
shape="square"
                            >人脸识别（限1张）：
                        </van-checkbox>
                        <van-uploader
                            v-model="fileList"
                            multiple
                            max-count="1"
                            :disabled="!disabled"
                            :after-read="afterRead"
                            :before-delete="beforeDelete"
                        />
                        <div class="mjTypeBox">
                            <van-checkbox
name="3"
shape="square"
                                ><div class="mjType">IC卡：</div>
                            </van-checkbox>
                            <input
                                type="text"
                                placeholder="输入卡号"
                                :disabled="!readOnly2"
                                v-model="newWorker.iccardno"
                            />
                        </div>
                        <div class="mjTypeBox">
                            <van-checkbox
name="4"
shape="square"
                                ><div class="mjType">二维码</div>
                            </van-checkbox>
                        </div>
                    </van-checkbox-group>
                </li>
                <li class="titleLi titleLiLast">
                    <span class="required">*</span>
                    门禁权限：
                    <van-dropdown-menu>
                        <van-dropdown-item
                            v-model="value1"
                            :options="option1"
                            disabled
                        />
                    </van-dropdown-menu>
                </li>
                <li class="titleLi titTips">
                    说明：企业员工默认普通权限，如需特殊权限，请联系园区管理方。
                </li>
                <li class="titleLi">
                    入职日期：
                    <input
                        type="text"
                        placeholder="请选择"
                        readonly
                        @click="show = true"
                        v-model="newWorker.rzrq"
                    />
                </li>
                <li class="titleLi">
                    职位：
                    <input
                        type="text"
                        placeholder="请填写"
                        v-model="newWorker.zw"
                    />
                </li>
                <li class="titleLi">
                    学历：
                    <input
                        type="text"
                        placeholder="请填写"
                        v-model="newWorker.xl"
                    />
                </li>
                <li class="titleLi">
                    家庭住址：
                    <input
                        type="text"
                        placeholder="请填写"
                        v-model="newWorker.jtzz"
                    />
                </li>
                <li class="titleLi">
                    紧急联系人：
                    <input
                        type="text"
                        placeholder="请填写"
                        v-model="newWorker.jjlxr"
                    />
                </li>
                <li class="titleLi">
                    紧急联系人电话：
                    <input
                        type="text"
                        placeholder="请填写"
                        v-model="newWorker.jjlxrdh"
                    />
                </li>
                <li class="titleLi titleLiLast">
                    <!-- <span class="required">*</span> -->
                    学历证书（限1张）：
                </li>
                <li class="titleLi titleLiUploader2">
                    <van-uploader
                        v-model="fileList2"
                        multiple
                        max-count="1"
                        :after-read="afterRead2"
                        :before-delete="beforeDelete2"
                    />
                </li>
                <li class="titleLi titleLiLast">
                    其他证书或荣誉信息（限6张）：
                </li>
                <li class="titleLi titleLiUploader3">
                    <van-uploader
                        v-model="fileList3"
                        multiple
                        max-count="6"
                        :after-read="afterRead3"
                        :before-delete="beforeDelete3"
                    />
                </li>
                <li class="titleLi" v-show="$route.query.id">
                    员工当前状态：
                    <van-dropdown-menu>
                        <van-dropdown-item
                            v-model="workerType"
                            :options="workerTypeBox"
                            @change="changeType"
                        />
                    </van-dropdown-menu>
                </li>
                <li class="titleLi" v-show="newWorker.zt == '离职'">
                    离职日期：
                    <input
                        type="text"
                        placeholder="请选择"
                        readonly
                        @click="showOutTime"
                        v-model="newWorker.lzrq"
                    />
                </li>
            </ul>
            <!-- 时间弹出层 -->
            <van-popup
                v-model="show"
                position="bottom"
                :style="{ height: '50%' }"
            >
                <van-datetime-picker
                    v-model="currentDate"
                    type="date"
                    title="选择年月日"
                    :min-date="minDate"
                    :max-date="maxDate"
                    @cancel="show = false"
                    @confirm="selectTime"
            /></van-popup>
            <van-popup
                v-model="outTime"
                position="bottom"
                :style="{ height: '50%' }"
            >
                <van-datetime-picker
                    v-model="currentDate"
                    type="date"
                    title="选择年月日"
                    :min-date="minDate"
                    :max-date="maxDate"
                    @cancel="outTime = false"
                    @confirm="selectTime2"
            /></van-popup>
        </div>
        <div class="buttonBox">
            <button class="turnOff" @click="turnOff">关闭</button>
            <button
                class="preservation btn2"
                @click.stop="submit"
                v-show="isClick"
            >
                提交
            </button>
            <button class="preservation btn3" v-show="!isClick">
                处理中
            </button>
        </div>
    </div>
</template>
<script>
import { editInfo, workerInfo } from '@/service/api_worker.js'
import auth from '@/service/auth'
import { upload } from '@/service/api_upload'
import { Toast } from 'vant'
import constant from '@/common/js/constant'
export default {
    data() {
        return {
            isClick: true,
            readOnly: true,
            readOnly2: false,
            disabled: true,
            result: [],
            fileList: [],
            fileList2: [],
            fileList3: [],
            fileIdList3: [],
            value1: 0,
            sex: '男',
            option1: [
                { text: '普通权限（所在楼栋+公共区域）', value: 0 },
                { text: '特殊权限', value: 1 }
            ],
            option2: [{ text: '男', value: '男' }, { text: '女', value: '女' }],
            minDate: new Date(2000, 0, 1),
            maxDate: new Date(2025, 10, 1),
            currentDate: new Date(),
            show: false,
            outTime: false,
            intTime: '',
            newWorker: {
                id: '',
                qyid: auth.currUser().id,
                qymc: auth.currUser().qymc,
                shxydm: auth.currUser().shxydm,
                xm: '',
                xb: '男',
                sjhm: '',
                mjlx: '1,2',
                sfzmhm: '',
                rlzp: '',
                iccardno: '',
                permissions: 'ALL',
                rzrq: '',
                zw: '',
                xl: '',
                jtzz: '',
                jjlxr: '',
                jjlxrdh: '',
                xlzszp: '',
                qtzszp: '',
                zt: '在职',
                lzrq: ''
            },
            workerType: '在职',
            workerTypeBox: [
                { text: '在职', value: '在职' },
                { text: '离职', value: '离职' }
            ]
        }
    },
    created() {
        window.scrollTo({
            top: 0,
            left: 0,
            behavior: 'smooth'
        })
    },
    mounted() {
        console.log(auth.currUser())
        this.isUpDate()
    },
    methods: {
        turnOff() {
            this.$router.push('/personList')
        },
        // 修改员工状态
        changeType(e) {
            console.log(e)
            this.newWorker.zt = e
        },
        showOutTime() {
            this.outTime = true
        },
        // 判断是否为信息更新
        isUpDate() {
            if (this.$route.query.id) {
                workerInfo({ id: this.$route.query.id }).then(res => {
                    if (res.mjlx) {
                        this.result = res.mjlx.split(',')
                    }
                    if (res.permissions != 'ALL' || !res.permissions) {
                        this.value1 = 1
                    }
                    this.newWorker = res
                    if (res.rlzp) {
                        this.fileList.push(
                            JSON.parse(
                                '{"url":"' +
                                    constant.BASE_URI +
                                    '/wx/fileController/download/' +
                                    res.rlzp +
                                    '","isImage": true}'
                            )
                        )
                    }
                    if (res.xlzszp) {
                        this.fileList2.push(
                            JSON.parse(
                                '{"url":"' +
                                    constant.BASE_URI +
                                    '/wx/fileController/download/' +
                                    res.xlzszp +
                                    '","isImage": true}'
                            )
                        )
                    }
                    if (res.qtzszp) {
                        this.fileIdList3 = res.qtzszp.split(',')
                        this.fileIdList3.forEach(item => {
                            this.fileList3.push(
                                JSON.parse(
                                    '{"url":"' +
                                        constant.BASE_URI +
                                        '/wx/fileController/download/' +
                                        item +
                                        '","isImage": true}'
                                )
                            )
                        })
                    }
                })
                this.newWorker.id = this.$route.query.id
            }
        },
        selectTime(e) {
            const dayjs = require('dayjs')
            this.newWorker.rzrq = dayjs(e).format('YYYY-MM-DD')
            this.show = false
        },
        selectTime2(e) {
            const dayjs = require('dayjs')
            this.newWorker.lzrq = dayjs(e).format('YYYY-MM-DD')
            this.outTime = false
        },
        cjmjType(e) {
            this.newWorker.mjlx = e.toString()
            if (e.includes('1')) {
                this.readOnly = true
            } else {
                this.readOnly = false
            }
            if (e.includes('2')) {
                this.disabled = true
            } else {
                this.disabled = false
            }
            if (e.includes('3')) {
                this.readOnly2 = true
            } else {
                this.readOnly2 = false
            }
        },
        // 提交
        submit() {
            if (!this.newWorker.xm) {
                Toast('请输入姓名')
                return
            } else if (!this.newWorker.sjhm) {
                Toast('请输入手机号码')
                return
            } else if (
                !this.result.includes('2') &&
                !this.result.includes('3') &&
                !this.result.includes('4')
            ) {
                console.log(this.result)
                Toast('门禁类型请选择人脸或IC卡或二维码')
                return
            }

            const phoneReg = /(^1[3|4|5|6|7|8|9]\d{9}$)|(^09\d{8}$)/
            const sfzReg = /^(([1-9][0-9]{5}(19|20)[0-9]{2}((0[1-9])|(1[0-2]))([0-2][1-9]|10|20|30|31)[0-9]{3}([0-9]|X|x))|([1-9][0-9]{5}[0-9]{2}((0[1-9])|(1[0-2]))([0-2][1-9]|10|20|30|31)[0-9]{3}))$/
            // if (!phoneReg.test(this.newWorker.sjhm)) {
            //     Toast('请输入正确手机号')
            //     return
            // }

            // if (this.result.includes("1")) {
            //     if (!sfzReg.test(this.newWorker.sfzmhm)) {
            //         Toast("请输入正确身份证号");
            //         return;
            //     }
            //     if (!this.newWorker.sfzmhm) {
            //         Toast("请填写身份证");
            //         return;
            //     }
            // } else {
            //     this.newWorker.sfzmhm = "";
            // }

            if (this.result.includes('2')) {
                console.log(this.fileList)
                if (this.fileList.length == 0) {
                    Toast('请上传人脸照片')
                    return
                }
            } else {
                this.fileList = []
            }

            if (this.result.includes('3')) {
                if (!this.newWorker.iccardno) {
                    Toast('请填写IC卡')
                    return
                }
            } else if (this.result.includes('4')) {
                this.newWorker.iccardno = 'qrcode'
            } else {
                this.newWorker.iccardno = ''
            }
            // this.isClick = false;

            Toast.loading({
                message: '提交中...',
                forbidClick: true,
                duration: 0
            })
            editInfo(this.newWorker).then(res => {
                if (res.errmsg == '成功') {
                    Toast.clear()
                    // this.isClick = true;
                    this.$router.push('/personList')
                } else {
                    Toast.clear()
                }
                Toast(res.errmsg)
            })
        },
        afterRead(file) {
            Toast.loading({
                message: '上传中...',
                forbidClick: true,
                duration: 0
            })
            if (file instanceof Array) {
                file.map(v => {
                    this.uploadImg(v)
                })
            } else {
                this.uploadImg(file)
            }
        },
        beforeDelete(file, detail) {
            const vm = this
            // name.index代表图片的索引
            vm.newWorker.rlzp = ''
            this.fileList = []
        },
        uploadImg(file) {
            const _this = this
            const formParam = new FormData() // 创建form对象
            formParam.append('file', file.file) // 通过append向form对象添加数据
            const config = {
                headers: {
                    'Content-Type': 'multipart/form-data',
                    'MVVM-Key': String(new Date().getTime()),
                    xx: 'anything'
                } // 这里是重点，需要和后台沟通好请求头，Content-Type不一定是这个值
            } // 添加请求头
            return new Promise((resolve, reject) => {
                // axios.post('http://121.228.7.226:9001/wx/fileController/upload', formParam, config)
                upload(formParam, config)
                    .then(response => {
                        if (response.data.length) {
                            _this.newWorker.rlzp = response.data[0]
                        }
                        Toast.clear()
                    })
                    .catch((err, x) => {
                        reject(err, x)
                    })
            })
        },
        afterRead2(file) {
            Toast.loading({
                message: '上传中...',
                forbidClick: true,
                duration: 0
            })
            if (file instanceof Array) {
                file.map(v => {
                    this.uploadImg2(v)
                })
            } else {
                this.uploadImg2(file)
            }
        },
        beforeDelete2(file, detail) {
            const vm = this
            // name.index代表图片的索引
            vm.newWorker.xlzszp = ''
            this.fileList2 = []
        },
        uploadImg2(file) {
            const _this = this
            const formParam = new FormData() // 创建form对象
            formParam.append('file', file.file) // 通过append向form对象添加数据
            const config = {
                headers: {
                    'Content-Type': 'multipart/form-data',
                    'MVVM-Key': String(new Date().getTime()),
                    xx: 'anything'
                } // 这里是重点，需要和后台沟通好请求头，Content-Type不一定是这个值
            } // 添加请求头
            return new Promise((resolve, reject) => {
                // axios.post('http://121.228.7.226:9001/wx/fileController/upload', formParam, config)
                upload(formParam, config)
                    .then(response => {
                        if (response.data.length) {
                            _this.newWorker.xlzszp = response.data[0]
                        }
                        Toast.clear()
                    })
                    .catch((err, x) => {
                        reject(err, x)
                    })
            })
        },
        afterRead3(file) {
            Toast.loading({
                message: '上传中...',
                forbidClick: true,
                duration: 0
            })
            if (file instanceof Array) {
                file.map(v => {
                    this.uploadImg3(v)
                })
            } else {
                this.uploadImg3(file)
            }
        },
        beforeDelete3(file, detail) {
            const vm = this
            // name.index代表图片的索引
            vm.fileIdList3.splice(detail.index, 1)
            vm.newWorker.qtzszp = vm.fileIdList3.toString()

            return (file, name) => {
                const fileIndex = name.index
                vm.fileIdList3[detail.index].splice(fileIndex, 1)
            }
        },
        uploadImg3(file) {
            const _this = this
            const formParam = new FormData() // 创建form对象
            formParam.append('file', file.file) // 通过append向form对象添加数据
            const config = {
                headers: {
                    'Content-Type': 'multipart/form-data',
                    'MVVM-Key': String(new Date().getTime()),
                    xx: 'anything'
                } // 这里是重点，需要和后台沟通好请求头，Content-Type不一定是这个值
            } // 添加请求头
            return new Promise((resolve, reject) => {
                // axios.post('http://121.228.7.226:9001/wx/fileController/upload', formParam, config)
                upload(formParam, config)
                    .then(response => {
                        if (response.data.length) {
                            response.data.forEach(element => {
                                _this.fileIdList3.push(element)
                            })
                            _this.newWorker.qtzszp = _this.fileIdList3.toString()
                            console.log(_this.newWorker.qtzszp)
                        }

                        Toast.clear()
                    })
                    .catch((err, x) => {
                        reject(err, x)
                    })
            })
        }
    }
}
</script>
<style lang="scss">
.addStaff {
    font-size: 4vw;
    margin: 5vw 2vw;

    .secendPage {
        background: white;
        padding: 3vw 3vw 3vw 3vw;
        margin-top: 5vw;
        border-radius: 15px;

        li {
            display: flex;
            align-items: center;
            height: 10vw;
            padding: 5vw 0;
            border-bottom: 1px solid rgb(243, 236, 236);
        }

        .titleLi {
            font-size: 3.5vw;
            font-weight: 700;
            white-space: nowrap;
            .required {
                color: red;
            }
            .van-uploader {
                padding: 3vw 0;
            }
        }
        .titleLiRadio {
            .van-radio-group {
                display: flex;
                width: 100%;
                justify-content: space-evenly;
            }
        }
        .titleLiLast {
            border-bottom: none;
            padding-bottom: 0;
        }
        .titTips {
            color: lightgray;
            font-weight: 500;
            padding: 0 0;
            font-size: 2vw;
        }
        .titleLiUploader {
            padding: 22vw 0;
            overflow: visible;
            input {
                border: 1px solid lightgray;
                width: 60vw;
            }
            .mjType {
                display: inline-block;
                width: 13vw;
            }
            .mjTypeBox {
                display: flex;
            }
        }
        .titleLiUploader2 {
            padding: 8vw 0;
        }
        .titleLiUploader3 {
            padding: 18vw 0;
        }
        input {
            padding: 15px 0 15px 20px;
        }
        textarea {
            padding: 15px 0 15px 20px;
        }
    }

    .van-dropdown-menu__bar {
        box-shadow: none !important;
    }
    .buttonBox {
        background: white;
        display: flex;
        align-items: center;
        justify-content: space-evenly;
        margin-top: 5vw;
        margin-bottom: 0;
        padding: 5vw 0;
        button {
            padding: 2vw 10vw;
            border-radius: 15px;
        }
        .turnOff {
            background: white;
            border: 1px solid rgb(0, 47, 167);
            color: rgb(0, 47, 167);
        }
        .btn2 {
            background-color: rgb(0, 47, 167);
            color: white;
            border: white solid 1px;
        }
        .btn3 {
            background-color: rgb(38, 39, 43);
            color: white;
            border: white solid 1px;
        }
    }
    .van-popup {
        li {
            padding: 0 !important;
            border: none !important;
        }
    }
    .van-checkbox__icon--disabled .van-icon {
        background-color: #1989fa !important;
        border-color: #1989fa !important;
    }
    .van-checkbox__label--disabled {
        color: #323233 !important ;
    }
}
</style>
