<template lang="pug">
    el-dialog( :visible.sync='visible' class="myDialog"  append-to-body :before-close="handleClose")
        .title-bold(slot='title') {{id ? '编辑应急团队' :'新增应急团队'}}
        el-card.mycard(shadow="never" style='border:0;')
            el-form(:model='dataForm', :rules='dataRule', ref='dataForm',  label-width='100px')
                el-row(:gutter='20')
                    el-col(:span='12')
                        el-form-item(label="姓名:", prop="name")
                            el-input.mywidth(  v-model="dataForm.name" placeholder="姓名" clearable)
                    el-col(:span='12')
                        el-form-item(label='性别:', prop='gender')
                            el-radio-group(v-model='dataForm.gender')
                                el-radio(:label='1') 男
                                el-radio(:label='0') 女
                el-row(:gutter='20')
                    el-col(:span='12')
                        el-form-item(label='出生日期:', prop='birthday')
                            el-date-picker.mywidth(v-model='dataForm.birthday', type="date" value-format="yyyy-MM-dd" format="yyyy-MM-dd" placeholder='出生日期')
                    el-col(:span='12')
                        el-form-item(label='政治面貌:', prop='politicCountenance')
                            el-select.mywidth( v-model="dataForm.politicCountenance" @blur="checkRule('politicCountenance')" placeholder="请选择" clearable)
                                el-option(v-for="(item, index) in politicCountenances" :key='index' :label="item.name" :value="item.id")
                el-row(:gutter='20')
                    el-col(:span='12')
                        el-form-item(label='民族:', prop='nation')
                            el-select.mywidth( v-model="dataForm.nation" @blur="checkRule('nation')" placeholder="请选择" clearable)
                                el-option(v-for="(item, index) in nations" :key='index' :label="item.name" :value="item.id.toString()")
                    el-col(:span='12')
                        el-form-item(label='证件类型:', prop='cardType',)
                            el-select.mywidth( v-model="dataForm.cardType" @blur="checkRule('cardType')" placeholder="请选择" clearable)
                                el-option(v-for="(item, index) in cardTypeList" :key='index' :label="item.name" :value="item.id.toString()")
                el-row(:gutter='20')
                    el-col(:span='12')
                        el-form-item(label='证件号码:', prop='cardNumber',)
                            el-input.mywidth( v-model='dataForm.cardNumber', placeholder='证件号码')
                    el-col(:span='12')
                        el-form-item(label='移动电话:', prop='mobile')
                            el-input.mywidth( v-model='dataForm.mobile', placeholder='请填写移动电话号码')
                el-row(:gutter='20')
                    el-col(:span='24')
                        el-form-item(label='人员专长:', prop='types')
                            el-checkbox-group(v-model="dataForm.types" placeholder="人员专长" clearable)
                                el-checkbox(v-for="(item, index) in types" :key="index" :label="item.id") {{item.name}}
                    el-col(:span='24')
                        el-form-item(label='人员类型:', prop='personnelType')
                            el-radio-group(v-model='dataForm.personnelType')
                                el-radio(:label='1') 应急专家
                                el-radio(:label='2') 应急人员
                    el-col(:span='24')
                        el-form-item(label='人员说明:', prop='skill')
                            el-input.mywidth(type="textarea" :rows="4" resize='none'  v-model='dataForm.skill', placeholder='人员说明' clearable)
                    el-col(:span='24')
                        el-form-item(label='状态:', prop='status')
                            el-radio-group(v-model='dataForm.status')
                                el-radio(:label='1') 正常
                                el-radio(:label='0') 禁用
        span.dialog-footer(slot='footer')
            el-button(type='primary' size='medium' @click='cancel') 取消
            el-button(type='primary' size='medium' @click='dataFormSubmit' v-prevent-re-click) 保存
</template>

<script>
    // import { isEmail, isMobile } from '@/util/validate'

    export default {
        data() {
            // var validatecardNumber = (rule, value, callback) => {
            //     if (value === '') {
            //         callback(new Error('请输入身份证号码'))
            //     } else {
            //         if (!this.checkIDCard(value)) {
            //             callback(new Error('请输入正确的身份证号码'))
            //         }
            //         callback()
            //     }
            // }
            return {
                clickFlag: false,
                id: '',
                show: true,
                visible: false,
                roleList: [],
                sysOrgList: [],
                dataListSelections: [],
                nations: [],
                cardTypeList: [
                    { id: '1', name: '身份证' },
                    { id: '2', name: '工作证' },
                    { id: '3', name: '户籍证' },
                    { id: '4', name: '护照' }
                ],
                types: [
                    { id: '1', name: '医学救援' },
                    { id: '2', name: '消防' },
                    { id: '3', name: '抢险' },
                    { id: '4', name: '防爆' },
                    { id: '5', name: '谈判' },
                    { id: '6', name: '人道救援' }
                ],
                politicCountenances: [
                    { id: '1', name: '共青团员' },
                    { id: '2', name: '预备党员' },
                    { id: '3', name: '党员' },
                    { id: '4', name: '群众' },
                    { id: '5', name: '其它' }
                ],
                dataForm: {
                    name: '',
                    gender: '',
                    birthday: '',
                    politicCountenance: '',
                    nation: '',
                    cardNumber: '',
                    mobile: '',
                    types: [],
                    skill: '',
                    status: '',
                    cardType: '',
                    personnelType: ''
                },
                dataRule: {
                    name: [
                        { required: true, message: '姓名不能为空', trigger: 'blur' },
                        {
                            min: 1,
                            max: 30,
                            message: '长度在 1 到 30 个字符',
                            trigger: ['change', 'blur']
                        }
                    ],
                    gender: [{ required: true, message: '性别必须选择', trigger: 'change' }],
                    // birthday: [
                    //   { required: true, message: '生日不能为空', trigger: 'blur' }
                    // ],
                    politicCountenance: [
                        { required: true, message: '政治面貌不能为空', trigger: 'change' }
                    ],
                    // nation: [
                    //   { required: true, message: '民族不能为空', trigger: 'change' }
                    // ],
                    // cardType: [
                    //   { required: true, message: '证件类型不能为空', trigger: 'change' }
                    // ],
                    cardNumber: [
                        { required: true, message: '证件号码不能为空', trigger: 'blur' },
                        { max: 50, message: '长度不能超过50个字符', trigger: 'blur' }
                        // { validator: validatecardNumber, trigger: ['change', 'blur'] }
                    ],
                    mobile: [
                        { required: true, message: '移动电话不能为空', trigger: 'blur' },
                        { pattern: /^1[12345789]\d{9}$/, message: '请输入正确的移动电话号码' }
                    ],
                    types: [
                        { required: true, message: '人员专长必须选择', trigger: 'change' }
                    ],
                    personnelType: [
                        { required: true, message: '人员类型必须选择', trigger: 'change' }
                    ],
                    skill: [
                        { max: 300, message: '长度不能超过300个字符', trigger: 'blur' }
                    ]
                }
            }
        },
        mounted() {
            this.getNation()
            // this.getAllTypes()
            // this.getCardTypeList()
        },
        methods: {
            init(id) {
                // console.log(id);
                this.clickFlag = false
                this.visible = true
                this.id = id || null
                if (id) {
                    this.$http({
                        url: this.$http.adornUrl(`/emProficient/getId/` + id),
                        method: 'get'
                    }).then(data => {
                        let da = data.bean
                        da.types = da.types.split(',')
                        this.dataForm = da
                        // console.log('dataForm', this.dataForm)
                    })
                } else {
                    this.show = true
                    this.dataForm = {
                        name: '',
                        gender: '',
                        birthday: '',
                        politicCountenance: '',
                        nation: '',
                        cardNumber: '',
                        mobile: '',
                        types: [],
                        skill: '',
                        status: 1,
                        personnelType: ''
                    }
                }
            },
            checkRule(value) {
                // console.log("value", value);
                this.$refs.dataForm.validateField(value)
            },
            //身份证校验
            checkIDCard(idcode) {
                // 加权因子
                var weightFactor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
                // 校验码
                var checkCode = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']

                var code = idcode + ''
                var last = idcode[17] //最后一位

                var seventeen = code.substring(0, 17)

                // ISO 7064:1983.MOD 11-2
                // 判断最后一位校验码是否正确
                var arr = seventeen.split('')
                var len = arr.length
                var num = 0
                for (var i = 0; i < len; i++) {
                    num = num + arr[i] * weightFactor[i]
                }

                // 获取余数
                var resisue = num % 11
                var lastNo = checkCode[resisue]

                // 格式的正则
                // 正则思路
                /*
              第一位不可能是0
              第二位到第六位可以是0-9
              第七位到第十位是年份，所以七八位为19或者20
              十一位和十二位是月份，这两位是01-12之间的数值
              十三位和十四位是日期，是从01-31之间的数值
              十五，十六，十七都是数字0-9
              十八位可能是数字0-9，也可能是X
              */
                var idcardPatter = /^[1-9][0-9]{5}([1][9][0-9]{2}|[2][0][0|1][0-9])([0][1-9]|[1][0|1|2])([0][1-9]|[1|2][0-9]|[3][0|1])[0-9]{3}([0-9]|[X])$/

                // 判断格式是否正确
                var format = idcardPatter.test(idcode)

                // 返回验证结果，校验码和格式同时正确才算是合法的身份证号码
                return !!(last === lastNo && format)
            },
            //获取民族信息
            getNation() {
                this.$http({
                    url: this.$http.adornUrl('/emPerson/getAllNation'),
                    method: 'get'
                }).then(data => {
                    // console.log("data", data);
                    if (data && data.code === 0) {
                        this.nations = data.result
                    }
                })
            },
            //获取人员专长
            getAllTypes() {
                this.$http({
                    url: this.$http.adornUrl('/emPerson/getAllTypes'),
                    method: 'get',
                    params: { stationId: localStorage.getItem('stationId') }
                }).then(data => {
                    // console.log("data", data);
                    if (data && data.code === 0) {
                        this.types = data.result
                    }
                })
            },
            //获取政治面貌
            //- getAllPoliticCountenance () {
            //-   this.$http({
            //-     url: this.$http.adornUrl('/emPerson/getAllPoliticCountenance'),
            //-     method: 'get'
            //-   }).then(data => {
            //-     // console.log("data", data);
            //-     if (data && data.code === 0) {
            //-       this.politicCountenance = data.result
            //-     }
            //-   })
            //- },
            //获取证件类型
            getCardTypeList() {
                this.$http({
                    url: this.$http.adornUrl('/sysDictionary/getCardTypeList'),
                    method: 'get',
                    params: { stationId: localStorage.getItem('stationId') }
                }).then(data => {
                    if (data && data.code === 0) {
                        this.cardTypeList = data.list
                    }
                })
            },
            // 多选
            selectionChangeHandle(val) {
                this.dataListSelections = val
            },
            change() {
                this.$forceUpdate()
            },
            //格式化时间
            //- formatDate(time, format = 'YY-MM-DD hh:mm:ss') {
            //-     var date = new Date(time)

            //-     var year = date.getFullYear(),
            //-         month = date.getMonth() + 1, //月份是从0开始的
            //-         day = date.getDate(),
            //-         hour = date.getHours(),
            //-         min = date.getMinutes(),
            //-         sec = date.getSeconds()
            //-     var preArr = Array.apply(null, Array(10)).map(function (elem, index) {
            //-         return '0' + index
            //-     }) ////开个长度为10的数组 格式为 00 01 02 03

            //-     var newTime = format
            //-         .replace(/YY/g, year)
            //-         .replace(/MM/g, preArr[month] || month)
            //-         .replace(/DD/g, preArr[day] || day)
            //-         .replace(/hh/g, preArr[hour] || hour)
            //-         .replace(/mm/g, preArr[min] || min)
            //-         .replace(/ss/g, preArr[sec] || sec)

            //-     return newTime
            //- },
            // 表单提交
            dataFormSubmit() {
                this.$refs['dataForm'].validate(valid => {
                    if (valid) {
                        this.clickFlag = true
                        this.$http({
                            url: this.$http.adornUrl(
                                `/emProficient/${!this.dataForm.id ? 'save' : 'update'}`
                            ),
                            method: 'post',
                            data: {
                                id: this.dataForm.id,
                                name: this.dataForm.name,
                                gender: this.dataForm.gender,
                                birthday: this.dataForm.birthday,
                                politicCountenance: this.dataForm.politicCountenance,
                                nation: this.dataForm.nation,
                                cardType: this.dataForm.cardType,
                                cardNumber: this.dataForm.cardNumber,
                                mobile: this.dataForm.mobile,
                                types: this.dataForm.types.join(','),
                                skill: this.dataForm.skill,
                                status: this.dataForm.status,
                                personnelType: this.dataForm.personnelType,
                                stationId: localStorage.getItem('stationId')
                            }
                        }).then(data => {
                            // console.log(data, "======");
                            if (data && data.code === 0) {
                                this.$message({
                                    message: '操作成功',
                                    type: 'success',
                                    duration: 1500
                                })
                                this.handleClose()
                                this.$emit('refreshdatalist')
                                this.clickFlag = false
                            } else {
                                this.$message.error(data.msg)
                                this.clickFlag = false
                            }
                        })
                    }
                })
            },
            //关闭页面前调用
            handleClose() {
                this.visible = false
                this.$refs.dataForm.resetFields()
            },
            //取消
            cancel() {
            this.$confirm('确认取消?', this.id ? '编辑应急团队' : '新增应急团队', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                this.handleClose()
                })
                .catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消退出'
                })
                })
            }
        }
    }
</script>
<style lang="scss" scoped>
    .el-table__header {
        width: 100% !important;
    }

    .el-table__body {
        width: 100% !important;
    }
    .myDialog{
        /deep/.el-dialog{
            margin-top:4vh !important;
        }
    }
</style>
