<!-- 通用弹窗表单 -->
<template>
  <div>
  <Modal
    v-model="modal"
    :width="width"
    @on-cancel="cancel"
    class-name="vertical-center-modal"
  >
    <div class="title" slot="header">
      {{ title }}
    </div>
    <div slot="footer" class="footer" v-if="type !== 'form'">
      <Button @click="cfm" class="btn" type="primary">提交</Button>
      <Button @click="cancel" class="btn">取消</Button>
    </div>
    <div slot="footer" class="footer" v-else>
      <Button @click="cancel" class="btn" type="primary">关闭</Button>
    </div>
    <div class="content">
      <Form ref="form" :model="formData" :rules="ruleValidate">
          <Col :span="item.span || '24'" v-for="(item, index) in config" :key="index">
            <FormItem :prop="item.key" :label="item.label + '：'" :label-width="item.hiddenLabel? 0 : 100">
              <!-- 自定义标签 -->
              <div slot="label">
                {{ item.hiddenLabel? '' : item.label + '：' }}
              </div>
              <!-- 输入框 -->
              <Input
                v-if="item.type === 'input'"
                v-model="formData[item.key]"
                :placeholder="item.placeholder"
                :type="item.comType"
                :disabled="item.disabled"
                />
              <!-- 日期选择 -->
              <DatePicker
                v-if="item.type === 'date'"
                v-model="formData[item.key]"
                @on-change="handleDateChange(item.key)"
                :transfer="true"
                :type="item.comType"
                format="yyyy-MM-dd"
                :placeholder="item.placeholder"
                style="width: 100%"
              >
              </DatePicker>
              <!-- 下拉框 -->
              <Select v-if="item.type === 'select'" :transfer="true" v-model="formData[item.key]" style="max-width: 400px;" :disabled="item.disabled">
                <Option v-for="option in item.list" :value="option.value" :key="option.value">{{ option.label || '未知' }}</Option>
              </Select>
              <!-- 搜索下拉框 -->
              <Select v-if="item.type === 'selectSearch'" clearable filterable :transfer="true" v-model="formData[item.key]" style="max-width: 400px;" :disabled="item.disabled">
                <Option v-for="option in item.list" :value="option.value" :key="option.value">{{ option.label || '未知' }}</Option>
              </Select>
              <!-- 单选框 -->
              <RadioGroup v-if="item.type === 'radio'" v-model="formData[item.key]">
                <Radio :label="radio.value" v-for="radio in item.list" :key="radio.value">
                  <span>{{ radio.label }}</span>
                </Radio>
              </RadioGroup>
              <!-- 图片上传 -->
              <Upload
                v-if="item.type === 'upload' && !item.disabled"
                ref="upload"
                :before-upload="uploadOther"
                :format="['jpg','jpeg','png']"
                accept=".jpg,.png,.jpeg"
                action=""
                >
                <div style="display: flex;width: 100%;">
                  <Input v-model="formData[item.key]" style="flex: 1"/>
                  <Button type="primary" style="width: 120px;">{{ item.text }}</Button>
                </div>
              </Upload>
              <Input v-if="item.type === 'upload' && item.disabled" v-model="formData[item.key]" disabled/>
              <div v-if="item.type === ''" style="cursor: auto;">
                <Input style="opacity: 0;cursor: auto;" disabled/>
              </div>
            </FormItem>
          </Col>
      </Form>
    </div>
  </Modal>
</div>
</template>

<script>
import { UploadBase64, UploadBusinessLicense } from '@/api/upload'
import MyTable from '_c/my-table/my-table'

export default {
  components: {
    MyTable
  },
  props: {
    // 标题
    title: {
      type: String,
      default: ''
    },
    // 修改表单时的数据
    data: {
      type: Object,
      default () {
        return {}
      }
    },
    // 表单类型 add新增 edit修改 form查看
    type: {
      type: String,
      default: 'add'
    },
    // 表单校验格式
    ruleValidate: {
      type: Object,
      default () {
        return {}
      }
    },
    // 表单显示格式
    config: {
      type: Array,
      default () {
        return []
      }
    },
    // 是否显示表单
    value: {
      type: Boolean,
      default: false,
      require: true
    },
    width: {
      type: String,
      default: '500px'
    }
  },
  watch: {
    isMaterial () {
      console.log('isMaterial', this.isMaterial)
    },
    value: {
      handler (n) {
        this.modal = n
        // 表单数组绑定问题
        if (n) {
          setTimeout(() => {
            this.isFirst = false
          }, 100)
        } else {
          this.isFirst = true
          this.tabName = 0
        }
      },
      immediate: true
    },
    modal (n) {
      this.$emit('input', n)
    }
  },
  data () {
    return {
      isFirst: true,
      show: false,
      modal: false,
      formData: {
        materialCodeList: [],
        facPicList: []
      },
      piclistColumns: [
        {
          title: '序号',
          type: 'index',
          width: 60,
          align: 'center'
        },
        {
          title: '维护记录',
          key: 'title'
        },
        {
          title: '日期',
          key: 'createdTime'
        },
        {
          title: '附件',
          key: 'picUrl',
          tooltip: true,
          render: (h, params) => {
            return h('a', {
              on: {
                click () {
                  let newWindow = window.open()
                  newWindow.document.write("<br><div style='padding: 0'><img width='" + (100) + '%' + "' src='" + params.row.picUrl + "'/></div>")
                  newWindow.document.close()
                }
              }
            }, params.row.picUrl)
          }
        }
      ]
    }
  },
  methods: {
    // 时间控件选择
    handleDateChange (key) {
      this.formData[key] = this.$dayjs(this.formData[key]).format('YYYY-MM-DD')
    },
    // 上传运营执照 自动获取相关信息并回填
    uploadOther (file) {
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = (event) => {
        UploadBusinessLicense({
          base64str: event.srcElement.result
        }).then(res => {
          if (res.code === 0) {
            this.formData = { ...this.formData }
            this.$set(this.formData, 'name', res.result.name)
            this.$set(this.formData, 'legalPerson', res.result.legalPerson)
            this.$set(this.formData, 'societyCreditCode', res.result.societyCreditCode)
            this.$set(this.formData, 'registeredAddress', res.result.registeredAddress)
            this.$set(this.formData, 'establishDate', res.result.establishDate.replace('年', '-').replace('月', '-').replace('日', ''))
            this.$set(this.formData, 'enterpriseType', res.result.enterpriseType)
            this.$set(this.formData, 'businessScope', res.result.businessScope)
            this.$set(this.formData, 'registeredCapital', res.result.registeredCapital)
            this.$set(this.formData, 'businessTerm', res.result.businessTerm.replace('年', '-').replace('月', '-').replace('日', ''))
          }
        })
      }
      return false
    },
    // 图片上传
    upload (file) {
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = (event) => {
        UploadBase64({
          fileBase64: event.srcElement.result,
          fileName: file.name,
          floder: 'order'
        }).then(res => {
          if (res.code === 0) {
            this.$Message.info('上传成功')
            if (!this.formData.facPicList) {
              this.$set(this.formData, 'facPicList', [])
            }
            this.formData.facPicList.push({
              picUrl: res.result,
              createDate: this.$dayjs().format('YYYY-MM-DD')
            })
          }
        })
      }
      return false
    },
    // 选择物料
    materialHandle (item) {
      this.show = true
    },
    // 获从面料组件获取取选中面料
    getselectedList (list, multiple) {
      if (multiple) {
        for (const key in list) {
          this.formData[key] = list[key]
        }
      } else {
        this.formData.materialCodeList = []
        this.formData.materialNames = []
        for (const key in list) {
          this.$set(this.formData.materialCodeList, key, list[key].code)
        }
        for (const key in list) {
          this.$set(this.formData.materialNames, key, list[key].name)
        }
      }
    },
    cancel () {
      this.modal = false
      this.formData = {}
      this.$refs.form.resetFields()
    },
    cfm () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.type === 'edit') {
            this.$emit('confirm', 'edit', { ...this.formData })
            this.formData = {}
            this.$refs.form.resetFields()
          } else {
            this.$emit('confirm', 'add', { ...this.formData })
            this.formData = {}
            this.$refs.form.resetFields()
          }
        }
      })
    }
  },
  mounted () {
    // 不加第一次进来数据会绑定失败 修改的时候会校验失败
    this.formData = {}
  },
  beforeUpdate () {
    // 防止input type为number时绑定数据 校验失败
    if (this.isFirst) {
      if (this.modal && (this.type === 'edit' || this.type === 'form')) {
        for (const key in this.data) {
          if ((Number.parseFloat(this.data[key]) === 'NaN') || (typeof this.data[key] === 'object')) {
            this.formData[key] = this.data[key]
          } else if (key === 'sex') {
            this.$set(this.formData, 'sex', this.data.sexCode)
          } else if (this.data[key] || this.data[key] === 0) {
            this.formData[key] = this.data[key].toString()
          }
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
.content {
  .col {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    .label {
      width: 100px;
      text-align: right;
    }
  }
}
/deep/ .vertical-center-modal{
  display: flex;
  align-items: center;
  justify-content: center;
  .ivu-modal{
    top: 0;
  }
}
///deep/ .ivu-modal-content {
//  height: 80vh;
//  overflow: hidden;
//}
/deep/ .ivu-modal-body {
  max-height: ~"calc(80vh - 68px)";
  overflow: auto;
}
/deep/ .ivu-form-item {
  .ivu-form-item {
    margin-bottom: 24px;
  }
}
/deep/ .ivu-form-item-label {
  display: flex;
  justify-content: flex-end;
}
/deep/ .ivu-tabs {
  background-color: #f2f2f2;
  padding: 10px;
}
/deep/ .ivu-upload-select {
  width: 100%;
}
</style>
