<template>
  <div class="form-main">
    <a-card :body-style="{padding: '24px 32px'}" :bordered="false">
      <a-form @submit="handleSubmit" :form="form">

        <a-form-item
          label="报销金额"
          :labelCol="{lg: {span: 7}, sm: {span: 7}}"
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
        >
          <a-input
            placeholder="请输入数字"
            :disabled="disabled"
            v-decorator="[
            'money',
            {rules: [{ required: true, message: '请输入数字' }]}
          ]"
            name="money"
          />
        </a-form-item>
        <a-form-item
          label="报销类别"
          :labelCol="{lg: {span: 7}, sm: {span: 7}}"
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
        >
          <a-select
            placeholder="请选择"
            :disabled="disabled"
            show-search
            v-decorator="[
            'type',
            {rules: [{ required: true, message: '请选择类型' }]}
          ]"
          >
            <a-select-option v-for="d in typeData" :key="d.value">{{ d.text }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="费用明细"
          :labelCol="{lg: {span: 7}, sm: {span: 7}}"
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
        >
          <a-textarea
            placeholder="请输入费用明细描述"
            :disabled="disabled"
            v-decorator="['expense_details',{rules: [{ required: true, message: '请输入费用明细描述' }]}]"
            :auto-size="{ minRows: 3, maxRows: 5 }"
          ></a-textarea>
        </a-form-item>
        <a-form-item
          label="发票"
          :labelCol="{lg: {span: 7}, sm: {span: 7}}"
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
        >
          <a-select
            placeholder="请选择"
            :disabled="disabled"
            show-search
            v-decorator="[
            'invoice',
            {rules: [{ required: true, message: '请选择' }]}
          ]"
          >
            <a-select-option v-for="d in invoiceTypeList" :key="d.value">{{ d.text }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="图片"
          :labelCol="{lg: {span: 7}, sm: {span: 7}}"
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
        >
          <div class="clearfix">
            <a-upload
              action="/jeecg-boot/sys/common/uploadFile"
              list-type="picture-card"
              :multiple="true"
              :file-list="fileList"
              :disabled="disabled"
              @preview="handlePreview"
              @change="handleChange"
            >
              <div v-if="fileList.length < 8">
                <a-icon type="plus" />
                <div class="ant-upload-text">上传</div>
              </div>
            </a-upload>
            <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
              <img alt="example" style="width: 100%" :src="previewImage" />
            </a-modal>
          </div>
        </a-form-item>

        <a-form-item v-if="!disabled" :wrapperCol="{ span: 24 }" style="text-align: center">
          <a-button
            htmlType="submit"
            type="primary"
            :disabled="disabled||btndisabled"
            @click="handleSubmit"
          >保存</a-button>
          <a-button style="margin-left: 8px" :disabled="disabled" @click="close">取消</a-button>
        </a-form-item>
      </a-form>
    </a-card>
  </div>
</template>
<script>
import pick from 'lodash.pick'

export default {
  name: 'demoForm',
  props: {
    /*全局禁用，可表示查看*/
    disabled: {
      type: Boolean,
      default: false,
      required: false
    },
    /*流程数据*/
    processData: {
      type: Object,
      default: () => {
        return {}
      },
      required: false
    },
    /*是否新增*/
    isNew: { type: Boolean, default: false, required: false }
  },
  data() {
    return {
      url: {
        getForm: '/actBusiness/getForm',
        addApply: '/actBusiness/add',
        editForm: '/actBusiness/editForm',
        leaveType: '/sys/dict/getDictItems'
      },
      description: '流程表单demo，按例开发表单。需在 activitiMixin.js 中加入写好的表单',
      // form
      form: this.$form.createForm(this),
      /*表单回显数据*/
      data: {},
      btndisabled: false,
      // disabled:false,
      typeData: [],
      previewVisible: false,
      previewImage: '',
      fileList: [],//文件上传集合
      invoiceTypeList:[]
    }
  },
  created() {
    console.log('流程数据', this.processData)
    //获取报销类型下拉数据
    this.getAction(this.url.leaveType + '/reimbursement_type').then(res => {
      if (res.success) {
        this.typeData = res.result
      } else {
        this.$message.error(res.message)
      }
    })
    //获取发票类型下拉数据
    this.getAction(this.url.leaveType + '/invoice_type').then(res => {
      if (res.success) {
        this.invoiceTypeList = res.result
      } else {
        this.$message.error(res.message)
      }
    })

    if (!this.isNew) {
      // this.disabled=true;
      this.init()
    } else {
      // this.btndisabled = false;
      // this.disabled=false;
    }
  },
  methods: {
    /*回显数据*/
    init() {
      this.btndisabled = true

      var r = this.processData
      // if(!r.tableId){
      //   return;
      // }
      this.getAction(this.url.getForm, {
        tableId: r.tableId,
        tableName: r.tableName
      }).then(res => {
        if (res.success) {
          let formData = res.result
          formData.tableName = r.tableName
          this.data = formData
          console.log('表单回显数据', this.data)
          this.$nextTick(() => {
            // this.form.setFieldsValue(pick(this.data,'type'))
            console.log('表单回显数据', this.data.start_time)
            this.fileList = JSON.parse(JSON.stringify(res.result.childList))
            this.getFileList()
            console.log(this.fileList)
            this.form.setFieldsValue({
              money: this.data.money,
              type: this.data.type,
              expense_details: this.data.expense_details,
              invoice: this.data.invoice
            })
            // this.form.setFieldsValue(moment(this.data.end_time,'end_time'))
          })
          this.btndisabled = false
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // handler
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          let formData = Object.assign(this.data || {}, values)
          formData.procDefId = this.processData.id
          formData.procDeTitle = this.processData.name
          if (!formData.tableName) formData.tableName = this.processData.businessTable
          formData.filedNames = _.keys(values).join(',')+",table_name_b"
          var url = this.url.addApply
          if (!this.isNew) {
            url = this.url.editForm
          }
          //获取文件集合
          formData.table_name_b = 'cd_reimbursement_file' //子表表名
          formData.childList = '' //子表数据
          let childList = []
          if (this.fileList != null && this.fileList.length > 0) {
            this.fileList.forEach(element => {
              childList.push({ file_url: element.response.message })
            })
            formData.filedNamesB = _.keys(childList[0]).join(',') //子表字段名
          }
          formData.childList = JSON.stringify(childList) //子表数据转义
          this.btndisabled = true
          this.postFormAction(url, formData)
            .then(res => {
              if (res.success) {
                this.$message.success('保存成功！')
                this.$emit('afterSubmit', formData)
              } else {
                this.$message.error(res.message)
              }
            })
            .finally(() => {
              this.btndisabled = false
            })
        }
      })
    },
    close() {
      this.$emit('close')
    },
    //文件控件处理
    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
    },
    //选择文件确定事件
    handleChange({ fileList }) {
      console.log(fileList)
      this.fileList = fileList
    },
    //详情修改查看
    getFileList() {
      //文件集合不为空则显示文件下载
      if (this.fileList && this.fileList != null && this.fileList.length > 0) {
        this.fileList.forEach((element, index) => {
          const fileName = setAppendix(element)
          ;(element.uid = '-1'),
            (element.uid = index + 1),
            (element.name = fileName),
            (element.status = 'done'),
            (element.url = '/jeecg-boot/sys/common/downloadFile/' + element.file_url)
          element.response = { message: element.file_url }
        })
      }
    }
  }
}

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

//显示路径
function setAppendix(file) {
  const url = file.fileUrl
  if (url != null && url !== '') {
    const idx = url.lastIndexOf('/')
    const fileUrl = url.slice(idx + 1)
    const index = fileUrl.lastIndexOf('_')
    const i = fileUrl.lastIndexOf('.')
    const fileName = fileUrl.substring(0, index)
    const fileSuffix = fileUrl.slice(i + 1)
    const f = fileName + '.' + fileSuffix
    return f
  }
  return ''
}
</script>
<style lang="less" scoped>
.form-main {
}
</style>