<template>
    <div class="TranslatorBase-all">
        <el-dialog top="8vh" width="1000px" title="翻译人员信息" :visible.sync="TranslatorBaseform"  :close-on-click-modal="false">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px"
                class="demo-ruleForm form-style">
                <el-form-item label="所在地区" prop="area">
                    <el-input v-model="ruleForm.area"></el-input>
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="ruleForm.name"></el-input>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="ruleForm.sex">
                        <el-radio label="男"></el-radio>
                        <el-radio label="女"></el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="证件照" prop="photo">
                    <el-upload class="avatars-uploader" action="" :show-file-list="false"
                        :on-change="handleAvatarchange">
                        <img v-if="imageUrl" :src="imageUrl" class="avatars">
                        <i v-else class="el-icon-plus avatars-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <div class="pj-form">
                    <el-form-item label="联系电话" prop="tel">
                        <el-input v-model="ruleForm.tel"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱号" prop="email">
                        <el-input v-model="ruleForm.email"></el-input>
                    </el-form-item>
                    <el-form-item label="微信号" prop="wechatNo">
                        <el-input v-model="ruleForm.wechatNo"></el-input>
                    </el-form-item>
                    <el-form-item label="其他账号" prop="otherSocialAccounts">
                        <el-input v-model="ruleForm.otherSocialAccounts"></el-input>
                    </el-form-item>
                    <el-form-item label="语种" prop="language">
                        <el-input v-model="ruleForm.language"></el-input>
                    </el-form-item>
                    <el-form-item label="关联公务">
                        <el-form :inline="true" :model="pageParams.params" class="demo-form-inline">
                            <select-tree :data="getData" :defaultCheckedKeys="pusharr" :filterable="true" @selectTerrEvent="selectTerrEvetn"
                                :defaultExpandAll="true" :defaultProps="defaultProps">
                            </select-tree>
                        </el-form>
                        
                        <!-- <el-select multiple collapse-tags filterable v-model="ruleForm.officialDutyIdItem"
                            placeholder="请选择公务">
                            <el-option v-for="(item,index) in officialDutyData" :key="index" :label="item.client"
                                :value="item.id"></el-option>
                        </el-select> -->
                    </el-form-item>
                </div>
                <el-form-item label="费用" prop="price">
                    <el-input-number :precision="2" placeholder="邀请费用" v-model="ruleForm.price"
                        :controls='false'></el-input-number>
                </el-form-item>
                <el-form-item label="币种" prop="currency">
                    <el-select filterable v-model="ruleForm.currency" placeholder="请选择币种">
                        <el-option v-for="(item,index) in currencyarr" :key="index" :label="item.name"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item></el-form-item>
                <el-form-item style="width:100%" label="简历/证书">
                    <el-upload class="upload-demo" ref="upload" action="" :multiple="true" :on-change="handleChange"
                        :on-preview="handlePreview" :on-remove="handleRemove" :file-list="fileList"
                        :auto-upload="false">
                        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                        <!-- <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button> -->
                        <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
                    </el-upload>
                </el-form-item>
                <el-form-item style="width:100%" label="备注">
                    <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="ruleForm.remark">
                    </el-input>
                </el-form-item>
                <div class="TranslatorBase-form-btn">
                    <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
                    <!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
                </div>
            </el-form>
        </el-dialog>
        <div class="TranslatorBase-title">
            <div>翻译人员库</div>
        </div>
        <div class="TranslatorBase-search">
            <div class="TranslatorBase-search-ul">
                <div class="TranslatorBase-search-li">
                    <label>翻译人姓名</label>
                    <el-input size="small" placeholder="请输入内容" v-model="input" clearable></el-input>
                </div>
                <div class="TranslatorBase-search-li">
                    <el-button size="small" @click="TranslatorLibraryItem()" type="primary">查询</el-button>
                </div>
                <!-- <div class="TranslatorBase-search-li">
                    <label>请输入内容</label>
                    <el-input size="small" placeholder="请输入内容" v-model="input" clearable></el-input>
                </div>
                <div class="TranslatorBase-search-li">
                    <label>请输入内容</label>
                    <el-input size="small" placeholder="请输入内容" v-model="input" clearable></el-input>
                </div>
                <div class="TranslatorBase-search-li">
                    <label>请输入内容</label>
                    <el-input size="small" placeholder="请输入内容" v-model="input" clearable></el-input>
                </div> -->
            </div>
            <div>
                <el-button size="small" @click="abbtlbBtn" type="primary">新增</el-button>
            </div>
        </div>
        <div class="TranslatorBase-table">
            <el-table :data="tableData" border style="width: 100%" :cell-class-name="addClass">
                <el-table-column prop="area" label="地区" width="180">
                </el-table-column>
                <el-table-column prop="name" label="姓名" width="100">
                </el-table-column>
                <el-table-column prop="sex" label="性别" width="60">
                </el-table-column>
                <el-table-column prop="tel" label="电话" width="120">
                </el-table-column>
                <el-table-column prop="email" label="邮箱" width="120">
                </el-table-column>
                <el-table-column prop="wechatNo" label="微信" width="120">
                </el-table-column>
                <el-table-column prop="price" label="费用" width="120">
                    <template slot-scope="scope">
                        {{townum(scope.row.price)}}
                    </template>
                </el-table-column>
                <el-table-column prop="currency" label="币种" width="100">
                </el-table-column>
                <el-table-column prop="createUserName" label="录入人" width="100">
                </el-table-column>
                <el-table-column prop="createTime" label="录入时间" width="180">
                </el-table-column>
                <el-table-column prop="remark" label="备注">
                </el-table-column>
                <el-table-column label="操作" width="180">
                    <template slot-scope="scope">
                        <el-button @click="edittib(scope.$index, scope.row)" size="mini">编辑</el-button>
                        <el-button @click="TranslatorLibraryDel(scope.row)" size="mini" type="danger">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="block">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="currentPage" :page-sizes="[5, 10, 20, 50]" :page-size="currentsize"
                    layout="total, sizes, prev, pager, next, jumper" :total="total">
                </el-pagination>
            </div>
        </div>
    </div>
</template>
<script>
import SelectTree from './selectTree.vue'
export default {
    components: {
      SelectTree
    },
    data() {
        return {
            token:'',
            input: '',
            tableData: [],
            currentPage:1,
            currentsize:10,
            total:0,
            TranslatorBaseform: false,
            Id:0,
            ruleForms:new FormData(),
            ruleForm: {
                area:'',
                name: '',
                sex:'',
                photo:'',
                tel:'',
                email:'',
                wechatNo:'',
                otherSocialAccounts:'',
                officialDutyIdItem:[],
                language:'',
                price:0,
                currency:'',
                files:[],
                remark:'',
                region: '',
            },
            currencyarr:[],
            officialDutyData:[],
            opStatus:1,
            rules: {
                area: [
                    { required: true, message: '请输入所在地区', trigger: 'blur' },
                ],
                name: [
                    { required: true, message: '请输入姓名', trigger: 'blur' },
                ],
                sex: [
                    { required: true, message: '请选择性别', trigger: 'change' },
                ],
                tel: [
                    { required: true, message: '请输入联系电话', trigger: 'blur' },
                ],
                email: [
                    { required: true, message: '请输入邮箱号', trigger: 'blur' },
                ],
                wechatNo: [
                    { required: true, message: '请输入微信号', trigger: 'blur' },
                ],
                otherSocialAccounts: [
                    { required: true, message: '请输入其他账号', trigger: 'blur' },
                ],
                language: [
                    { required: true, message: '请输入语种', trigger: 'blur' },
                ],
                price: [
                    { required: true, message: '请输入费用', trigger: 'blur' },
                ],
                currency: [
                    { required: true, message: '请选择币种', trigger: 'change' },
                ],
            },

            //touxiang
            imageUrl: '',
            //附件
            fileList:[],


            pageParams:{},
            defaultProps: {
                children: "children",
                label: "label"
            },
            getData: [],
                
            pusharr:[]
            }
    },
    
    methods: {

        selectTerrEvetn(data) {
            this.ruleForm.officialDutyIdItem=[];
            for(let i=0;i<data.length;i++){
                this.ruleForm.officialDutyIdItem.push(data[i].id)
            }
            console.log(this.ruleForm.officialDutyIdItem)
        },
        //保留两位小数
        townum(val){
            val=Number(val);
            return val.toFixed(2);
        },
        //获取基础数据
        TranslatorLibraryInit(){
            var that = this;
            var url = "/api/Resource/TranslatorLibraryInit"
            this.$axios({
                method: 'get',
                url: url,
            }).then(function (res) {
                if (res.data.code == 200) {
                    that.currencyarr=res.data.data.currencyData;
                    that.officialDutyData=res.data.data.officialDutyData;
                    that.getData=res.data.data.officialDutyData;
                } else {
                    that.$message.error(res.data.msg);
                }
            })
        },
        //表单初始化
        formInitialization(){
            this.imageUrl='';
            this.fileList=[];
            this.ruleForm= {
                area:'',
                name: '',
                sex:'',
                photo:'',
                tel:'',
                email:'',
                wechatNo:'',
                otherSocialAccounts:'',
                language:'',
                price:0,
                currency:'',
                files:[],
                remark:'',
                region: '',
                officialDutyIdItem:[]
            }
        },
        //删除
        TranslatorLibraryDel(val){
            this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            type: 'warning'
            }).then(() => {
                var that = this;
                var url = "/api/Resource/TranslatorLibraryDel/id?id="+val.id
                this.$axios({
                    method: 'delete',
                    url: url,
                    headers: {
                        Authorization: 'Bearer '+that.token,
                    },
                }).then(function (res) {
                    if (res.data.code == 200) {
                        that.$message({
                            message: res.data.msg,
                            type: 'success'
                        });
                        that.TranslatorLibraryItem();
                    } else {
                        that.$message.error(res.data.msg);
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });
        },
        //新增
        abbtlbBtn(){
            this.Id=0;
            this.opStatus=1;
            this.formInitialization();
            this.$nextTick(() => {  this.$refs['ruleForm'].clearValidate();});
            this.TranslatorBaseform=true;
        },
        //编辑
        edittib(index,val){
            this.formInitialization();
            this.opStatus=2;
            // this.$nextTick(() => {  this.$refs['ruleForm'].clearValidate();});
            this.TranslatorBaseform=true;
            console.log(val);
            var that = this;
            var url = "/api/Resource/TranslatorLibraryInfo/id?id="+val.id
            this.$axios({
                method: 'get',
                url: url,
            }).then(function (res) {
                if (res.data.code == 200) {
                    that.Id=res.data.data.id;
                    that.ruleForm.area=res.data.data.area;
                    that.ruleForm.name=res.data.data.name;
                    that.ruleForm.sex=res.data.data.sex==2?'女':'男';
                    that.ruleForm.tel=res.data.data.tel;
                    that.ruleForm.email=res.data.data.email;
                    that.ruleForm.wechatNo=res.data.data.wechatNo;
                    that.ruleForm.otherSocialAccounts=res.data.data.otherSocialAccounts;
                    that.ruleForm.language=res.data.data.language;
                    that.ruleForm.price=res.data.data.price;
                    that.ruleForm.currency=res.data.data.currency;
                    that.ruleForm.photo=res.data.data.photo;
                    that.ruleForm.remark=res.data.data.remark;
                    that.ruleForm.officialDutyIdItem=res.data.data.officialDutyIdItem;
                    that.pusharr=res.data.data.officialDutyIdItem;
                    that.imageUrl=res.data.data.photo;
                    if (res.data.data.filePaths!=[]) {
                        for(let i=0;i<res.data.data.filePaths.length;i++){
                            that.fileList.push({'name':res.data.data.filePaths[i].fileName,'url':res.data.data.filePaths[i].filePathName})
                        }
                    }
                } else {
                    that.$message.error(res.data.msg);
                }
            })
        },
        //base转图片
        base64ImgtoFile(dataurl, filename = 'file') {
            if(dataurl==""){
                return
            }
            let arr = dataurl.split(',')
            let mime = arr[0].match(/:(.*?);/)[1]
            let suffix = mime.split('/')[1]
            let bstr = atob(arr[1])
            let n = bstr.length
            let u8arr = new Uint8Array(n)
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n)
            }
            return new File([u8arr], `${filename}.${suffix}`, {
                type: mime
            })
        },
        //获取列表
        TranslatorLibraryItem(){
            var that = this;
            var url = "/api/Resource/TranslatorLibraryItem"
            this.$axios({
                method: 'post',
                url: url,
                data:{
                    portType:1,
                    pageIndex: that.currentPage,
                    pageSize:  that.currentsize,
                    name: that.input
                }
            }).then(function (res) {
                if (res.data.code == 200) {
                    that.tableData=res.data.data;
                    that.total=res.data.count;
                } else {
                    that.$message.error(res.data.msg);
                }
            })
        },
        handleSizeChange(val) {
            this.currentsize=val;
            this.TranslatorLibraryItem();
        },
        handleCurrentChange(val) {
            this.currentPage=val;
            this.TranslatorLibraryItem();
        },
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.TranslatorLibraryOp()
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        //头像
        handleAvatarchange(file){
            if (file.status !== 'ready') return;
            const isJPG = file.raw.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
                return this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                return this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            this.imageUrl = URL.createObjectURL(file.raw);
            this.getBase64(file)
        },
        //base64转译
        getBase64(e) {
			// 选择的文件
			let file = e.raw;
            // 判断文件是否读取完毕，读取完毕后执行
            if (window.FileReader) {
                let reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = e => {
                    let base64String = e.target.result;
                    // 此处可对该base64进行获取赋值传入后端
                    this.ruleForm.photo=base64String;
                    console.log(base64String);
                }
            }
        },

        //附件
        // 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用,function(file, fileList)
        handleChange(file, fileList) {
            console.log(fileList);
            
            this.fileList = fileList;
            // if (file.status !== 'ready') return;
            // this.ruleForms = new FormData()
            // this.fileList.forEach((file) => {
            //     if(file.raw!=undefined){
            //         this.ruleForms.append('files',file.raw);
            //     }
            // })
            // console.log(formData);
            // this.ruleForm.files=formData
            console.log(this.ruleForms);
 
        },
        //保存
        TranslatorLibraryOp(){
            console.log(this.ruleForm.officialDutyIdItem);
            
            // return
            var ruleForms=new FormData();
            ruleForms.append('portType',1);
            ruleForms.append('status',this.opStatus);
            ruleForms.append('id',this.Id);
            ruleForms.append('area',this.ruleForm.area);
            ruleForms.append('name',this.ruleForm.name);
            ruleForms.append('sex',this.ruleForm.sex=='男'?1:2);
            ruleForms.append('photo',this.ruleForm.photo);
            ruleForms.append('tel',this.ruleForm.tel);
            ruleForms.append('email',this.ruleForm.email);
            ruleForms.append('wechatNo',this.ruleForm.wechatNo);
            ruleForms.append('otherSocialAccounts',this.ruleForm.otherSocialAccounts);
            ruleForms.append('language',this.ruleForm.language);
            ruleForms.append('price',this.ruleForm.price);
            ruleForms.append('currency',this.ruleForm.currency);
            ruleForms.append('remark',this.ruleForm.remark);
            // ruleForms.append('officialDutyIdItem',this.ruleForm.officialDutyIdItem);
            this.ruleForm.officialDutyIdItem.forEach((item,index)=>{
                ruleForms.append(`officialDutyIdItem[${index}]`,item);
            })
            // ruleForms.getAll('officialDutyIdItem[]');
            this.fileList.forEach((file) => {
                if (file.status == 'ready') {
                    if(file.raw!=undefined){
                        ruleForms.append('files',file.raw);
                    }
                }
            })
            var that = this;
            var url = "api/Resource/TranslatorLibraryOp"
            this.$axios({
                method: 'post',
                url: url,
                headers: {
                    Authorization: 'Bearer '+that.token,
                    'Content-Type':'multipart/form-data'
                },
                data:ruleForms
                    
            }).then(function (res) {
                if (res.data.code == 200) {
                    that.$message({
                        message: res.data.msg,
                        type: 'success'
                    });
                    that.TranslatorBaseform=false;
                    that.TranslatorLibraryItem();
                } else {
                    that.$message.error(res.data.msg);
                }
            })
        },
        //条件颜色
        addClass({row,column,rowIndex,columnIndex}){
            if(row.lastUpdateDays >= 365){
                    return 'cell-grey';
            }
        },
        submitUpload() {
            this.$refs.upload.submit();
        },
        handleRemove(file, fileList) {
            console.log(file, fileList);
        },
        handlePreview(file) {
            window.open(file.url)
            console.log(file);
        }
    },
    created(){
        
    },
    mounted(){
        this.token = JSON.parse(localStorage.getItem('userinif')).token;
        this.TranslatorLibraryInit();
        this.TranslatorLibraryItem();
    }
}
</script>
<style>
.TranslatorBase-all {
    background-color: #fff;
    padding: 10px;
    box-shadow: 0 0 5px #0005;
    border-radius: 10px;
    min-height: 830px;
}

.TranslatorBase-title {
    display: flex;
    font-size: 17px;
    font-weight: 600;
    color: #555;
    margin-top: 8px;
    margin-bottom: 10px;
    justify-content: space-between;
    align-items: center;

}

.TranslatorBase-search {
    display: flex;
    justify-content: space-between;
}

.TranslatorBase-search-ul {
    display: flex;
}

.TranslatorBase-search-li {
    width: 300px;
    display: flex;
    align-items: center;
    margin-right: 10px;
}

.TranslatorBase-search-li label {
    color: #606266;
    width: 100px;
}

.TranslatorBase-table {
    margin-top: 10px;
}
.form-style{
    display: flex;
    flex-wrap:wrap ;
    justify-content: space-between;
}
.form-style .el-form-item{
    width:33%;
}
.TranslatorBase-form-btn{
     text-align: right;
     width: 100%;
}
.form-style .avatars-uploader .el-upload{
    width: 100%;
}
.form-style .el-select{
    width: 100%;
}
.form-style .el-input-number{
    width: 100%;
}
.form-style .el-upload-list{
    display: flex;
    flex-wrap: wrap;
    align-items: center;
}
.form-style .el-upload-list__item{
    width: 50%;
}
.TranslatorBase-table .block{
    text-align: center;
    margin-top: 15px;
}
.pj-form{
    width:66.5%;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
}
.pj-form .el-form-item{
    width:49.5%;
}

.avatars-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatars-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatars-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatars {
    width: 178px;
    height: 178px;
    display: block;
}
.el-select-dropdown{
    width: 400px;
}
.select-tree .el-tag.el-tag--info{
    max-width: 125px;
}
.TranslatorBase-all .cell-grey{
    color: red;
}
</style>
