<template>
  <div class="dialogSty">
    <el-dialog
      :title="dialogForm.title"
      :visible.sync="dialogForm.dialogVisible"
      width="960px"
      @close="handleClose">
      <el-row>
        <el-form :model="form" :rules="rules" ref="form" label-width="130px" class="demo-ruleForm">
          <el-col :span="12">
            <el-form-item label="所属组织:" prop="orgId">
              <el-cascader
                :options="organizationOption"
                :props="organizationProps"
                ref="cascader"
                @change="handleOrgChange"
                style="width: 100%"
                v-model="form.orgId"
                filterable
                clearable
                placeholder="请选择所属气站"
                collapse-tags></el-cascader>
<!--              <el-select v-model="form.orgId" style="width: 100%;" multiple   placeholder="请选择所属气站" clearable>-->
<!--                <el-option v-for="item in organizationOption" :key="item.value" :label="item.label" :value="item.value">-->
<!--                </el-option>-->
<!--              </el-select>-->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号(账号):" prop="phone">
              <el-input v-model="form.phone" style="width: 100%;" :disabled="dialogType == 'edit'" @change="phoneChange" maxLength="11" placeholder="请输入人员联系电话" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名:" prop="name">
              <el-input v-model="form.name" placeholder="请输入人员姓名" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入职时间:" prop="employmentDate">
              <el-date-picker
                style="width: 100%;"
                v-model="form.employmentDate"
                type="date"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                placeholder="选择入职时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态:" prop="state">
              <el-select v-model="form.state" style="width: 100%;"  placeholder="请选择人员状态" clearable>
                <el-option v-for="item in statusOption" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色名称:" prop="roleName">
              <el-select v-model="form.roleName" style="width: 100%;" multiple   placeholder="请选择人员角色状态" clearable>
                <el-option v-for="item in roleOptions" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别:">
              <el-select v-model="form.gender" style="width: 100%;"  placeholder="请选择人员性别" clearable>
                <el-option v-for="item in genderOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号:">
              <el-input v-model="form.card" style="width: 100%;" placeholder="请输入人员身份证号" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行证书编号:">
              <el-input v-model="form.certificateNo" placeholder="请输入执行证书编号" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行证书有效期限:">
              <el-date-picker
                style="width: 100%;"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
                v-model="form.certificateValidityDate"
                type="date"
                placeholder="请选择执行证书有效期限">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注:">
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入备注信息"
                v-model="form.remark">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="fileSty">
            <el-form-item label="执行证书">
              <el-upload
                :file-list="fileList"
                :action="action"
                accept=".jpg,.jpeg,.png"
                list-type="picture-card"
                multiple
                :on-success="handleImgSuccess"
                :before-upload="beforeAvatarUpload"
                :on-remove="handleRemove"
                :on-preview="handlePictureCardPreview"
                :http-request="httpRequest">
                <i class="el-icon-plus"></i>
                <div class="el-upload__text">上传图片</div>
                <div class="el-upload__tip" slot="tip">支持：jpg/png/gif/ico/jpeg/gpg/gif/jpeg，不超过6MB，</div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="fileSty">
            <el-form-item label="身份证照片:">
              <el-upload
                :file-list="pictureFileList"
                :action="action"
                list-type="picture-card"
                multiple
                :show-file-list="true"
                :http-request="httpPictureRequest"
                :before-upload="beforeAvatarUpload"
                :on-preview="handlePictureCardPreview"
                :on-remove="handlePictureCardRemove">
                <i class="el-icon-plus"></i>
                <div class="el-upload__text">上传图片</div>
                <div class="el-upload__tip" slot="tip">可上传多张</div>
                <div class="el-upload__tip" slot="tip">支持：jpg/png/gif/ico/jpeg/gpg/gif/jpeg，不超过6MB，</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancel('form')">取 消</el-button>
        <el-button type="primary" @click="handleSubmit('form')">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import {queryUserDetail,queryUserInfo,addAndEditUser,queryStationInfo,getTreeNode} from '@/api/userManage'
import req from '@/utils/request.js'
export default {
  name: "dialogInfo",
  props:{
    orgId:{
      type:String,
      default:''
    }
  },
  data(){
    return{
      form:{
        id:'',
        orgId:[],
        orgid:'',
        phone:'',
        name:'',
        employmentDate:'',
        state:'',
        roleName:'',
        roleCode:'',
        gender:'',
        card:'',
        certificateNo:'',
        certificateValidityDate:'',
        remark:'',
        lx:'',
        fuserID:''
      },
      roles:[],
      roleOptions:[],
      genderOptions:[
        {
          label:'男',
          value:'男'
        },
        {
          label:'女',
          value:'女'
        }
      ],
      fileList:[],
      pictureFileList:[],
      rules:{
        orgId:[
          {
            required: true, message: '请选择所属的气站', trigger: 'change'
          }
        ],
        phone:[
          {
            required: true, message: '请输入人员联系电话', trigger: 'change'
          },
          {
            pattern:/^1[3|4|5|6|7|8|9][0-9]\d{8}$/,message: '请输入正确的手机号码'
          }
        ],
        name:[
          {
            required: true, message: '请输入人员姓名', trigger: 'change'
          },
        ],
        employmentDate:[
          {
            required: true, message: '请选择入职时间', trigger: 'change'
          }
        ],
        state:[
          {
            required: true, message: '请选择人员状态', trigger: 'change'
          }
        ],
        roleName:[
          {
            required: true, message: '请选择人员状态', trigger: 'change'
          }
        ]
      },
      dialogForm:{
        title:'新增用户',
        dialogVisible:false
      },
      dialogType:'add',
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      organizationOption:[],
      organizationProps:{value: 'id', label: 'name', children: 'children', multiple: false, checkStrictly: true,   },
      statusOption:[
        {
          label:'正常',
          value:'正常'
        },
        {
          label:'停用',
          value:'停用'
        }
      ],
      action:'',
      otherRoleList:[]
    }
  },
  created() {
    this.action = `${window.context.portal}/system/file/v1/fileUpload`;
  },
  mounted() {
    this.initData();
  },
  methods:{
    async initData(){
     await this.getOrgData();
    },
    //打开弹窗功能
   async open(type,row){
      // this.initData();
      this.dialogType = type;
      console.log('打印row',row);
      console.log('打印type',type);
      await this.initData();
      this.dialogForm.dialogVisible = true;
      this.$nextTick(()=>{
        this.$refs.form.resetFields();
      });
      this.form.name = '';
      this.form.gender ='';
      this.form.orgid = '';
      this.form.orgId =[];
      this.form.fuserID ='';
      this.form.state = '';
      this.fileList = [];
      this.form.remark ='';
      this.form.employmentDate ='';
      this.form.card ='';
      this.form.certificateValidityDate ='';
      this.form.certificateNo ='';
      this.pictureFileList =[];
      this.form.id ='';
      this.form.phone= '';
      if(this.orgId && type=='add'){
        console.log('打印this.orgD',this.orgId,this.organizationOption)
        let orgIdList = [];
        let orgLx = '';
        let orgID = '';
        this.organizationOption.map((item)=>{
          if(item.id == this.orgId){
            orgLx = item.lx;
            orgID = item.id;
            orgIdList.push(item.id);
          }else{
            item.children.map((vitem)=>{
              if(vitem.id == this.orgId){
                orgIdList.push(item.id);
                orgLx = vitem.lx;
                orgID = vitem.id;
                orgIdList.push(vitem.id);
              }
            })
          }
        });
        this.form.lx = orgLx;
        this.getRoleData(orgLx);
        this.form.orgid = orgID;
        this.$nextTick(() => {
          // this.$forceUpdate();
          // this.form.orgId =JSON.parse(JSON.stringify(orgIdList));
          // this.$set(this.form, "orgId", orgIdList);
          this.form.orgId = orgIdList;
          console.log('打印this.form.orgId====>',this.form.orgId,orgIdList)
        })
        // this.form.orgId =JSON.parse(JSON.stringify(orgIdList)) ;
        // this.form.orgId = ['1794993089828380672', '1794995745808474112']
      }
      if(row){
        this.form.id = row.id;
        await this.getUserDetail(row.id);
      }
    },
    async getOrgData(){
      await getTreeNode().then((res)=>{
        console.log('打印res',res);
        const { value } = res;
        const { children } = value;
        // this.organizationOption = children;
        this.organizationOption = this.handleTreeList(children)
        console.log('打印this.treeDAta',this.organizationOption);
      })
    },
    handleOrgChange(val){
      console.log('打印val',val);
      if(val.length>0){
        this.form.roleName = [];
        const checkedNodes = this.$refs.cascader.getCheckedNodes();
        this.form.lx = checkedNodes[0].data.lx;
        this.form.orgid = checkedNodes[0].data.id;
        this.getRoleData(this.form.lx );
        console.log('打印val',val,checkedNodes[0],this.form.orgId);
      }else{
        this.form.orgid = '';
      }
    },
    phoneChange(val){
      let testPhone = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/;
      if(val){
        let checkPhone= testPhone.test(val);
        console.log('打印checkPhone',checkPhone);
        if(checkPhone){
          let params = {
            phone:val
          }
          this.getUserInfo(params);
        }
      }
      console.log('打印val',val);

    },
    async getRoleData(lx){
      console.log('打印是否出发这个事件getRoleData',lx)
      let lxString = lx +'角色';
      let params ={
        lx:lxString
      }
      await queryStationInfo(params).then((res)=>{
        console.log('打打应res',res);
        const { value } = res;
        this.roleOptions = value;
      })
    },
    handleTreeList(list) { // 删除第三级children
      for (var i = 0; i < list.length; i++) {
        if (list[i].children.length < 1) {				// 判断children的数组长度
          list[i].children = undefined
        } else {
          this.handleTreeList(list[i].children)
        }
      }
      return list
    },
    async getUserDetail(id){
      let params ={
        id:id
      }
      await queryUserDetail(params).then((res)=>{
        const { value } = res;
        let orgLx = '';
        let orgID = '';
        console.log('打印value',value,this.organizationOption,value.orgId)
        this.form.employmentDate = value.employmentDate;
        this.form.gender = value.gender;
        this.form.phone = value.phone;
        this.form.state = value.state;
        this.form.name = value.name;
        this.form.card = value.card;
        this.form.fuserID = value.fuserID;
        this.form.certificateNo = value.certificateNo;
        this.form.certificateValidityDate = value.certificateValidityDate;
        this.form.remark = value.remark;
        let cardPictureUrlList = value.cardUrl?JSON.parse(value.cardUrl):[];
        let cardUrlList = [];
        cardPictureUrlList.map(async(item)=>{
          let imgUrl = await this.$getPhotoUrl(item.fileId);
          cardUrlList.push(({
            url:imgUrl,
            fileObj: JSON.stringify(item)
          }))
        });
        let certificateUrlList =value.certificateUrl? JSON.parse(value.certificateUrl):[];
        console.log('打印certificateUrlList',certificateUrlList)
        let certificateUrlList1 = [];
        certificateUrlList.map(async(item)=>{
          let imgUrl = await this.$getPhotoUrl(item.fileId);
          certificateUrlList1.push(({
            url:imgUrl,
            fileObj: JSON.stringify(item)
          }))
        });
        this.pictureFileList = cardUrlList;
        this.fileList = certificateUrlList1;
        let orgIdList = [];
        this.organizationOption.map((item)=>{
          if(item.id == value.orgId){
            orgLx = item.lx;
            orgID = item.id;
            orgIdList.push(item.id);
          }else{
            orgIdList.push(item.id);
            item.children.map((vitem)=>{
              if(vitem.id == value.orgId){
                orgLx = vitem.lx;
                orgID = vitem.id;
                orgIdList.push(vitem.id);
              }
            })
          }
        });
        this.form.lx = orgLx;
        this.getRoleData(orgLx);
        this.form.orgid = orgID;
        this.form.orgId = orgIdList;
        this.form.roleName = value.roles.map((item)=>item.id);
        console.log('打印queryUserDetail====>res',orgIdList);
      })
    },
   async getUserInfo(params){
      await queryUserInfo(params).then((res)=>{
        const { value } = res;
        let orgLx = '';
        if(value.length>0){
          let userInfo = value[0];
          this.form.name = userInfo.name;
          this.form.employmentDate = userInfo.employmentDate;
          this.otherRoleList = userInfo.roles;
          this.form.remark = userInfo.remark;
          this.form.gender = userInfo.gender;
          this.form.fuserID = userInfo.fuserID;
          this.form.state = userInfo.state;
        }

        console.log('打印是否触发通过手机号查询用户信息',res,this.form);
      })
    },
    handleCancel(formName){
      this.$refs[formName].resetFields();
      this.dialogForm.dialogVisible = false;
    },
    handleSubmit(formName){
      let roleDataList=  this.roleOptions.filter(item => this.form.roleName.some(x => x === item.id ));
      let roleDataList1 = [...new Set([...this.otherRoleList, ...roleDataList])];;
      const uniqueItems = roleDataList1.filter((item, index, self) =>
        index === self.findIndex((t) => t.id === item.id)
      );
      let roleNameString = uniqueItems.map(item => item.name).join(',')
      let roleCodeString = uniqueItems.map(item => item.code).join(',')
      let rolesList = uniqueItems.map(item => {
        return {
          id:item.id,
          name:item.name,
          code:item.code
        }
      });
      console.log('打印roleDataList',rolesList,roleCodeString,roleDataList,roleNameString);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let filePhotoList = this.fileList.map(item => JSON.parse(item.fileObj));
          let certificateUrlList = JSON.stringify(filePhotoList);
          let filePictureList = this.pictureFileList.map(item => JSON.parse(item.fileObj));
          let cardUrlList = JSON.stringify(filePictureList);
          let employmentDateString = this.form.employmentDate?this.parseTime(this.form.employmentDate,"{y}-{m}-{d}") +' 00:00:00':'';
          let certificateValidityDateString =this.form.certificateValidityDate?this.parseTime(this.form.certificateValidityDate,"{y}-{m}-{d}")+' 00:00:00':'';
          let params={
            id:this.form.id,
            orgId:this.form.orgid,
            phone:this.form.phone?this.form.phone:'',
            name:this.form.name,
            employmentDate:employmentDateString,
            state:this.form.state,
            certificateNo:this.form.certificateNo,
            certificateValidityDate:certificateValidityDateString,
            roleName:roleNameString,
            roleCode:roleCodeString,
            gender:this.form.gender,
            card:this.form.card,
            remark:this.form.remark,
            roles:rolesList,
            fuserID:this.form.fuserID,
            certificateUrl:certificateUrlList,
            cardUrl:cardUrlList,
          }
          console.log('打印params',params);
          addAndEditUser(params).then((res)=>{
            if(res.code == 200){
              this.$message.success(res.message);
              this.$emit('closeDialog')
            }else{
              this.$message.error(res.message);
            }
            this.dialogForm.dialogVisible = false;

            console.log('打印新增编辑的res',res);
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    handleRemove(file, fileList){
      console.log(file, this.fileList);
      const index = this.fileList.findIndex((item) => {
        return item.uid === file.uid
      })
      this.fileList.splice(index, 1)
    },
    // 自定义上传
    async httpRequest(val) {
      console.log('打印val',val);
      const formData = new FormData();
      formData.append('files', val.file);
      let response = await req.post(
        window.context.portal + '/system/file/v1/fileUpload',
        formData
      )
      if (response.success) {
        console.log('打印response',response);
        this.$message.success('上传成功');
        let imgUrl = response.fileId;
        if (response.fileId) {
          imgUrl = await this.$getPhotoUrl(response.fileId);
        }
        this.fileList.push({
          fileId:response.fileId,
          url:imgUrl,
          fileObj: JSON.stringify(response)
        });
        // this.form.fileId = response.fileId;
        // this.form.userId = this.$store.state.user.userInfo.user.userId
      }
    },
    // 身份证图片自定义上传
    async httpPictureRequest(val){
      console.log('打印val',val);
      const formData = new FormData();
      formData.append('files', val.file);
      let response = await req.post(
        window.context.portal + '/system/file/v1/fileUpload',
        formData
      )
      if (response.success) {
        console.log('打印response',response);
        this.$message.success('上传成功');
        let imgUrl = response.fileId;
        if (response.fileId) {
          imgUrl = await this.$getPhotoUrl(response.fileId);
        }
        this.pictureFileList.push({
          fileId:response.fileId,
          url:imgUrl,
          fileObj: JSON.stringify(response)
        });
        // this.form.fileId = response.fileId;
        // this.form.userId = this.$store.state.user.userInfo.user.userId
      }
    },
    handlePictureCardRemove(file, fileList) {
      console.log(file, this.pictureFileList);
      const index = this.pictureFileList.findIndex((item) => {
        return item.uid === file.uid
      })
      this.pictureFileList.splice(index, 1);
    },
    handleImgSuccess(val, e, el) {
      console.log('打印val',e,el);
      if (e.response.code != 0) {
        this.$message.error(e.response.msg);
        return false;
      }
      //文件上传成功，清空提示信息
      // this.$refs.repairForm.clearValidate();
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        this.$message.success("上传成功");
      }, 200);
      this.fileList = el;
      console.log(this.fileList, "this.fileList");
    },
    beforeAvatarUpload(file){
      console.log('打印beforeAvatarUpload===>file,file',file)
      let imgType = ["jpg", "jpeg", "png"];
      let judge = false; // 后缀
      let type = file.name.split(".")[file.name.split(".").length - 1];
      for (let k = 0; k < imgType.length; k++) {
        if (imgType[k].toUpperCase() === type.toUpperCase()) {
          judge = true;
          break;
        }
      }
      // 验证图片格式
      if (!judge) {
        this.$message.error("图片格式只支持：JPG、JPEG、PNG");
        return false;
      }
      const isLt1M = file.size / 1024 / 1024;
      if (isLt1M > 1) {
        this.$message.error("上传头像图片大小不能超过1MB");
        return false;
      }
      return true;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleDownload(file) {
      console.log(file);
    },
    //关闭弹窗功能
    handleClose(){

    },
  }
}
</script>

<style lang="scss" scoped>
.dialogSty{
  .fileSty{
    ::v-deep.el-upload--picture-card{
      position: relative;
    }
    .el-upload__text{
      position: absolute;
      top: 20px;
      left: 45px;
      font-family: '苹方 中等', '苹方', sans-serif;
      font-weight: 400;
      font-style: normal;
      font-size: 14px;
      color: #98A4B4;
    }
  }
}

</style>
