/*
 *@description:证件上件共用组件
 *@author: hudw
 *@date: 2022-03-14 10:40:55
*/

<template>
  <div>
    <a-modal ref="imgView" :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
    <a-modal v-model="sVisible" v-bind="modalConfig" :confirmLoading="confirmLoading" @ok="handleOk">
      <p-grid-form ref="grid" selfUpdate :span="12" :labelCol="{ span: 6 }" :wrapperCol="{ span: 16 }" :items="items">
        <div class="clearfix" slot="photo" style="margin: 0">
          <a-upload
            :remove="handleRemove"
            list-type="picture-card"
            :before-upload="beforeUpload"
            :file-list="fileList"
            accept="image/jpeg,image/png"
            @preview="handlePreview"
            :showUploadList="{ showRemoveIcon: view < 3 }"
            @change="handleChange"
          >
            <div v-if="view < 3 && fileList.length < 4">
              <a-icon type="plus" />
              <div class="ant-upload-text">上传图片</div>
            </div>
          </a-upload>
        </div>
        <!-- <div class="clearfix" slot="photo2" style="margin: 0">
          <a-upload
            :remove="handleRemove"
            list-type="picture-card"
            :before-upload="beforeUpload"
            :file-list="fileList"
            accept="image/jpeg,image/png"
            @preview="handlePreview"
            :showUploadList="{ showRemoveIcon: view < 3 }"
            @change="handleChange"
          >
            <div v-if="view < 3 && fileList.length < 4">
              <a-icon type="plus" />
              <div class="ant-upload-text">上传图片</div>
            </div>
          </a-upload>
        </div> -->
      </p-grid-form>
    </a-modal>
  </div>
</template>
<script>
import { setFormItems, updateImg, getPaperId } from './setConfig.js'
import { initDictionary } from '@/blocks/utils'
import { UPCLOUD_RDC_TMS_IMAGE_HOST } from '@/config/serviceSettings.js'

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => {
      return resolve(reader.result)
    }
    reader.onerror = (error) => reject(error)
  })
}
let options = null

export default {
  name: 'updateFormModal',
  props: {
    /**0=不显示, 1=新建，2=修改 ，3=查看 */
    view: 0,
    title: '',
    visible: false,
    columns: [],
    targetKeys: [],
    currentData: null,
    imgFile: [],
    //   {
    //   uid: '-1',
    //   name: 'image.png',
    //   status: 'done',
    //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
    // },
    //true:缓存数据跟主表一起保存，false:直接调接口保存提交
    btnSave: false, //直接调接口保存提交
  },

  computed: {
    modalConfig() {
      const { title } = this
      return { title, width: 740 }
    },
  },
  data() {
    return {
      options: options,
      confirmLoading: false,
      items: setFormItems(this, this.view),
      sVisible: this.visible,
      previewVisible: false,
      previewImage: '',
      cacheFile: [],
      fileList: [],
      laterFileList: [], //之后新加入的
      basePicture:[],
    }
  },

  watch: {
    currentData(data) {
      if (data?.picture) {
        this.basePicture= data.picture.split(',')
      }
    },
    visible(value) {
      this.sVisible = value
      if (value) {
        if (this.view === 1) {
          getPaperId().then((res) => {
            if (res.success && res.data) {
              this.$refs.grid.form.setFieldsValue({ id: res.data })
            } else {
              this.$exception(res)
            }
          })
        }
      }
    },
    sVisible(value) {
      this.cacheFile = []
      this.fileList = []
      this.confirmLoading = false
      if (value && this.view > 0) {
        this.items = setFormItems(this, this.view)
        this.$nextTick(() => {
          this.$refs.grid.form.resetFields()
          this.fileList = this.basePicture.map((str,index) => {
          return {
            uid:index,
            name: str,
            status: 'done',
            url:  UPCLOUD_RDC_TMS_IMAGE_HOST + '/' + str
          }
        })
          if (this.view > 1) {
            this.$refs.grid.form.setFieldsValue(this.currentData)
          }
        })
      } else {
        this.$nextTick(() => {
          this.items = []
        })
      }
      this.$emit('update:visible', value)
    },
  },
  mounted() {
    let _this = this
    if (!options) {
      initDictionary([{ objectcode: 'PAPER_TYPE' }]).then((res) => {
        _this.options = {}
        _this.options.PAPER_TYPE = res.PAPER_TYPE.map((item) => {
          item.value = +item.value
          return item
        })
        options = _this.options
      })
    }
  },
  methods: {
    handleCancel() {
      this.previewVisible = false
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },

    handleRemove(file) {
      this.basePicture=this.basePicture.filter(str => {
        return str!==file.name
      })
      this.fileList= this.fileList.filter(item => {

        return item.name!==file.name
      })
    },
    handleChange(obj) {
      const { fileList, file } = obj
      if (file.status == 'removed') {
          this.cacheFile = this.cacheFile.filter((item) => {
          return item.uid !== file.uid
        })
      }

      if (file.type === 'image/jpeg' || file.type === 'image/png') {
        this.fileList = fileList
      }
    },
    handleOk() {

      let _this = this
      this.$refs.grid.form.validateFields((errors, values) => {
        if (!errors) {
          let submit = async () => {
            _this.confirmLoading = true
            let formData = new FormData()
            let userinfo = this.$store.getters?.userInfo ?? null
            let size = 0
             values.picture= _this.basePicture
            if (_this.cacheFile.length === 0) {
              //没有加入新图片，就行list的数据返回
              values.picture=values.picture.join()
              return values
            }

            _this.cacheFile.forEach((file) => {
              size = +file.size
              formData.append('file', file)
            })
            console.log(size, 31457280)
            if (size > 31457280) {
              alert('文件上传过大')
            }
            formData.append('directory', '/tms')
            formData.append('storageType', 0)
            formData.append('isFileName', 0)
            return updateImg(this, formData)
              .then((response, reject) => {
                if (response.success) {
                  let fileList=response.data.map((item) => {
                    const { id, path, fileName } = item
                    return path
                  })
                  if (values.picture.length > 0) {
                    values.picture=values.picture.concat(fileList)
                  } else {
                    values.picture=fileList
                  }
                  values.picture = values.picture.join()
                  return values
                } else {
                  _this.$exception(response)
                  return null
                }
              })
              .finally(() => {
                _this.confirmLoading = false
                return null
              })
          }
          _this.$emit('ok', submit, () => {
            _this.confirmLoading = false
          })
          return
        }
      })
    },
    beforeUpload(file, fileList) {
      console.log(file)
      if (file.type === 'image/jpeg' || file.type === 'image/png') {
         this.cacheFile.push(file)
      } else {
        this.$exception({
          message:'图片格式不正确，请上传.jpg/.png文件'
        })
      }


      return false
    },
  },
}
</script>
<style scoped>
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
