<template>
  <a-modal
    title="企业信息"
    width="60%"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item label="名称" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
          <a-input
            placeholder="请输入企业名称"
            v-decorator="[
              'name',
              {
                validateFirst: true,
                rules: [
                  { required: true, message: '请输入企业名称' },
                  { max: 200, message: '名称最多200个字' }
                ]
              }
            ]"
          />
        </a-form-item>
        <a-form-item label="排序" help="数字越小越靠前" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
          <a-input placeholder="请输入排序号" type="number" v-decorator="['sortcode', { initialValue: 100 }]" />
        </a-form-item>
        <a-form-item label="职位" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input
            placeholder="请输入公司职位"
            v-decorator="[
              'pos',
              {
                validateFirst: true,
                rules: [
                  { required: true, message: '请输入公司职位' },
                  { max: 50, message: '职位最多50个字' }
                ]
              }
            ]"
          />
        </a-form-item>
        <a-form-item label="电话" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input
            placeholder="请输入公司电话"
            v-decorator="[
              'mobile',
              {
                validateFirst: true,
                rules: [
                  { required: true, message: '请输入公司电话' },
                  { max: 50, message: '电话最多50个字' }
                ]
              }
            ]"
          />
        </a-form-item>
        <a-form-item label="地址" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-cascader
            :options="area"
            placeholder="请选择地区"
            @change="regionChange"
            v-decorator="[
              'area',
              {
                validateFirst: true,
                rules: [{ required: true, message: '请选择地区' }]
              }
            ]"
          >
          </a-cascader>
        </a-form-item>
        <a-form-item label="详细地址" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-textarea
            :rows="4"
            placeholder="请输入详细地址"
            v-decorator="[
              'address',
              {
                validateFirst: true,
                rules: [
                  { required: true, message: '请输入详细地址' },
                  { max: 200, message: '详细地址最多200个字' }
                ]
              }
            ]"
          />
        </a-form-item>
        <a-form-item label="年收入(万元)" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input
            placeholder="请输入年收入"
            type="number"
            v-decorator="[
              'yearlyincome',
              {
                validateFirst: true,
                rules: [
                  {
                    validator: (rule, value, callback) => {
                      if (value < 0) {
                        callback('年收入不可小于0')
                      } else {
                        callback()
                      }
                    }
                  }
                ]
              }
            ]"
          />
        </a-form-item>
        <a-form-item label="年税收(万元)" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input
            placeholder="请输入年税收"
            type="number"
            v-decorator="[
              'yearlytax',
              {
                validateFirst: true,
                rules: [
                  {
                    validator: (rule, value, callback) => {
                      if (value < 0) {
                        callback('年税收不可小于0')
                      } else {
                        callback()
                      }
                    }
                  }
                ]
              }
            ]"
          />
        </a-form-item>
        <a-form-item label="员工人数" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input
            placeholder="请输入员工人数"
            type="number"
            v-decorator="[
              'staffcnt',
              {
                validateFirst: true,
                rules: [
                  {
                    validator: (rule, value, callback) => {
                      if (value < 0) {
                        callback('人数不可小于0')
                      } else {
                        callback()
                      }
                    }
                  }
                ]
              }
            ]"
          />
        </a-form-item>
        <a-form-item label="Logo" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
          <a-upload
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            v-decorator="['logo']"
            :customRequest="handleUpload"
          >
            <img v-if="logourl" style="max-height:200px;max-width:400px;" :src="logourl" alt="Logo" />
            <div v-else>
              <a-icon :type="uploading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">
                上传Logo
              </div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="企业图片" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
          <a-upload
            :action="uploadurl"
            list-type="picture-card"
            :file-list="fileList"
            @change="handleChange"
            @preview="handlePreview"
            :headers="handleComUploadHeader()"
          >
            <div v-if="fileList.length < 4">
              <a-icon type="plus" />
              <div class="ant-upload-text">
                上传
              </div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="企业介绍" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-textarea
            :rows="4"
            placeholder="请输入企业介绍"
            v-decorator="[
              'desc',
              {
                validateFirst: true,
                rules: [{ max: 2000, message: '企业介绍最多2000个字' }]
              }
            ]"
          />
        </a-form-item>
      </a-form>
    </a-spin>
    <a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
      <img alt="图片" style="width: 100%" :src="previewImage" />
    </a-modal>
  </a-modal>
</template>

<script>
import { GetClientDataList } from '@/utils/clientdata'
import { sysUserOwnCom, sysUserSubmitCom } from '@/api/modular/system/userManage'
import { UploadImg } from '@/api/modular/main/upload'
const areadata = require('@/utils/areadata.json')
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)
  })
}
export default {
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      loading: false,
      logourl: '',
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 15 }
      },
      currentInfo: {},
      area: areadata,
      uploadurl: '/api/common/uploadimg',
      visible: false,
      previewVisible: false,
      previewImage: '',
      uploading: false,
      confirmLoading: false,
      cominfo: {},
      fileList: [],
      form: this.$form.createForm(this)
    }
  },
  methods: {
    GetClientDataList,
    // 初始化方法
    init(record) {
      this.visible = true
      this.currentInfo = record
      this.logourl = ''
      this.uploading = false
      this.detail()
    },
    detail() {
      sysUserOwnCom({
        id: this.currentInfo.id
      }).then(res => {
        if (res.code === 0 && res.data) {
          this.cominfo = res.data
          this.logourl = res.data.logourl
          this.form.setFieldsValue({
            name: res.data.name,
            pos: res.data.pos,
            mobile: res.data.mobile,
            yearlyincome: res.data.yearlyincome,
            yearlytax: res.data.yearlytax,
            staffcnt: res.data.staffcnt,
            desc: res.data.desc,
            logo: res.data.logo,
            area: [res.data.province, res.data.city, res.data.area],
            address: res.data.address,
            sortcode: res.data.sortcode
          })
          this.fileList = res.data.pics.map((item, index) => {
            return {
              uid: index,
              name: item.path,
              status: 'done',
              url: item.url
            }
          })
        }
      })
    },
    handleSubmit() {
      const {
        form: { validateFields }
      } = this
      this.confirmLoading = true
      validateFields((errors, values) => {
        if (!errors) {
          values['userid'] = this.currentInfo.id ? this.currentInfo.id : null
          values['pics'] = this.fileList.map(item => item.name)
          values['id'] = this.cominfo.id ? this.cominfo.id : null
          if (values['area'].length !== 3) {
            this.$message.error('请选择地址')
            return
          }
          values['province'] = values['area'][0]
          values['city'] = values['area'][1]
          values['area'] = values['area'][2]
          sysUserSubmitCom(values)
            .then(res => {
              if (res.code === 0) {
                if (this.currentInfo && this.currentInfo.id) {
                  this.$message.success('编辑成功')
                } else {
                  this.$message.success('添加成功')
                }
                this.confirmLoading = false
                this.$emit('ok', this.record)
                this.handleCancel()
              } else {
                this.$myerror(res.message)
              }
            })
            .finally(res => {
              this.confirmLoading = false
            })
        } else {
          this.confirmLoading = false
        }
      })
    },
    // 地区选择
    regionChange(data, selectedOptions) {},
    // 上传
    handleUpload(data) {
      const formData = new FormData()
      formData.append('file', data.file)
      this.uploading = true
      UploadImg(formData).then(res => {
        if (res.code === 0) {
          this.logourl = res.data.url
          this.form.setFieldsValue({
            logo: res.data.path
          })
        } else {
          this.$myerror(res.message)
        }
        this.uploading = false
      })
    },
    // 企业图片上传头
    handleComUploadHeader() {
      return {
        Authorization: 'Bearer ' + this.$store.getters.token
      }
    },
    handleCancel() {
      this.form.resetFields()
      this.visible = false
    },
    handleChange({ file, fileList }) {
      if (file.response) {
        if (file.response.code !== 0) {
          this.$message.error(file.response.message)
          fileList.map(item => {
            if (item.uid === file.uid) {
              item.status = 'error'
            }
            return item
          })
          return
        } else {
          fileList.map(item => {
            if (item.uid === file.uid) {
              item.status = 'done'
              item.name = file.response.data.path
              item.url = file.response.data.url
            }
            return item
          })
        }
      }
      this.fileList = fileList
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    }
  }
}
</script>
