<template>
  <a-modal
    :title="title"
    :width="width"
    :bodyStyle="bodyStyle"
    @ok="handleOk"
    @cancel="handleCancel"
    :maskClosable="false"
    :footer="null"
    :visible="visible">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">

        <a-form-item label="身份证照片" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-upload
            name="file"
            :accept="accept"
            :remove="handleDelete"
            listType="picture"
            :multiple="true"
            :action="uploadAction"
            :headers="headers"
            :data="{'isup':1,'bizPath':bizPath}"
            :fileList="fileList"
            :beforeUpload="beforeUpload"
            @change="handleChange"
          >
            <a-button> <a-icon type="upload" /> 选择上传 </a-button>
          </a-upload>
        </a-form-item>

        <a-form-item label=" " :colon="false" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-button
            type="primary"
            @click="handleOk"
            :disabled="fileList.length === 0"
            :loading="confirmLoading"
          >
            {{confirmLoading ? '上传中' : '保存' }}
          </a-button>
        </a-form-item>
      </a-form>
    </a-spin>


  </a-modal>
</template>

<script>

  import { httpAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import Vue from 'vue'
  import JDate from '@/components/jeecg/JDate'
  import { ACCESS_TOKEN } from '@/store/mutation-types'

  const FILE_TYPE_ALL = "all"
  const uidGenerator = () => {
    return '-' + parseInt(Math.random() * 10000 + 1, 10)
  }
  const getFileName = (path) => {
    if (path.lastIndexOf('\\') >= 0) {
      let reg = new RegExp('\\\\', 'g')
      path = path.replace(reg, '/')
    }
    return path.substring(path.lastIndexOf('/') + 1)
  }

  export default {
    name: 'HlgUploadPhotoModal',
    components: {
      JDate,
    },
    data() {
      return {
        disableSubmit:false,
        options: [{
          value: '',
          label: '',
          isLeaf: false
        }],
        companyId: '',
        form: this.$form.createForm(this),
        picUrl: '',
        title: '操作',
        width: 800,
        bodyStyle: {
          paddingTop: '20px',
          paddingBottom:'50px',
          height: (window.innerHeight * 0.38) + 'px',
          'overflow-y': 'auto'
        },
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        uploadLoading: false,
        confirmLoading: false,
        headers: {},
        fileList:[],
        accept:'image/*',
        validatorRules: {

        },
        url: {
          add: '/hlguser/hlgUser/add',
          edit: '/hlguser/hlgUser/editIdcardPicture',
          fileUpload: window._CONFIG['domianURL'] + '/hpSys/common/ossUpload',
          imgerver: window._CONFIG['imgDomainOssURL'],
          hpWorkImgerver:window._CONFIG['imgHpworkDomainOssURL']
        }

      }
    },
    props: {
      fileType: {
        type: String,
        required: false,
        default: FILE_TYPE_ALL
      },
      /*这个属性用于控制文件上传的业务路径*/
      bizPath: {
        type: String,
        required: false,
        default: '/hlgjob/hlgUser'
      }
    },
    created() {
      const token = Vue.ls.get(ACCESS_TOKEN)
      this.headers = { 'X-Access-Token': token }

    },
    computed: {
      uploadAction: function() {
        return this.url.fileUpload
      }
    },
    methods: {
      add() {
        this.edit({})
      },
      edit(record) {
        this.form.resetFields()
        this.model = Object.assign({}, record);
        this.visible = true;
        //回显文件
        this.editFileList(this.model.idcardPicture)
        console.log(this.model.isImport)
      },
      close() {
        this.visible = false
      },

      //回显文件所用
      editFileList(paths) {
        if (!paths || paths.length == 0) {
          //return [];
          // update-begin- --- author:os_chengtgen ------ date:20190729 ---- for:issues:326,Jupload组件初始化bug
          this.fileList = []
          return
          // update-end- --- author:os_chengtgen ------ date:20190729 ---- for:issues:326,Jupload组件初始化bug
        }

        let fileList = []
        let arr = paths.split(',')
        for (var a = 0; a < arr.length; a++) {
          fileList.push({
            uid: uidGenerator(),
            name: getFileName(arr[a]),
            status: 'done',
            url: this.getAvatarView(arr[a]),
            thUrl: arr[a]
          })
        }
        this.fileList = fileList
      },


      beforeUpload: function(file) {
        var fileType = file.type
        if (fileType.indexOf('image') < 0) {
          this.$message.warning('请上传图片')
          return false
        }
        if (this.fileList.length>=2) {
          this.$message.warning('最多俩张图片')
          return false
        }
        //TODO 验证文件大小
      },
      handleChange(info) {
        let fileList = info.fileList
        //拦截长度
        if (info.fileList.length > 2) {
          return false
        }
        //拦截文件格式
        var fileType =info.file.type
        if (fileType.indexOf('image') < 0) {
          return false
        }

        if (info.file.status === 'done') {
          if (info.file.response.success) {
            fileList = fileList.map((file) => {
              if (file.response) {
                file.url = this.url.imgerver + file.response.message
                file.thUrl = file.response.message
              }
              return file
            })
          }
          this.$message.success(`${info.file.name} 上传成功!`)
        }else if (info.file.status === 'error') {
          this.$message.error(`${info.file.name} 上传失败.`)
        } else if (info.file.status === 'removed') {
          this.handleDelete(info.file)
        }
        this.fileList = fileList
      },
      getAvatarView(idcardPicture) {
          if( idcardPicture.indexOf("http")!=-1){
            return idcardPicture
          }else{
            return this.model.isImport==1?this.url.hpWorkImgerver+idcardPicture:this.url.imgerver+idcardPicture
          }
      },
      //移除文件
      handleDelete(file){
        const index = this.fileList.indexOf(file);
        const newFileList = this.fileList.slice();
        newFileList.splice(index, 1);
        this.fileList = newFileList;
      },

      //开始上传
      handleOk() {
        const that = this
        const { fileList } = that;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true
            let httpurl = ''
            let method = ''
            if (!this.model.id) {
              httpurl += this.url.add
              method = 'post'
            } else {
              httpurl += this.url.edit
              method = 'put'
            }
            var idcardPicture = "";
            let formData = Object.assign(this.model, values)
            let isDone = true;
            fileList.forEach((file,index) => {
              if(!file.thUrl){
                isDone = false;
              }
              if(index === 0){
                idcardPicture = file.thUrl;
              }else{
                idcardPicture += "," + file.thUrl;
              }
            });
            //上传文件出错
            if(!isDone){
              that.$message.error("正在上传，请稍后提交!");
              that.confirmLoading = false
              return;
            }
            formData.idcardPicture = idcardPicture;
            console.log('表单提交数据', formData)
            httpAction(httpurl, formData, method).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            }).finally(() => {
              that.confirmLoading = false
              that.close()
            })
          }

        })
      },
      handleCancel() {
        this.close()
      },
      popupCallback(row) {
        this.form.setFieldsValue(pick(row, 'idcardPicture'))
      },

    }
  }
</script>

<style lang="less" scoped>

</style>