<template>
  <div>
    <a-card :bordered="true" style="width: 100%">
      <template #title>
        <div style="font-size: 14px">
          <span style="color: red;margin-right: 8px">说明:</span>
          <span style="color: #666">企业介绍可体现公司的实力及产品的竞争力，增加海外客户的信任度，提升购买信心。</span>
        </div>
      </template>
      <a-spin :spinning="formSpinning" size="large">
        <a-form :form="form" v-if="this.siteList.length !== 0">
          <a-row>
            <a-col :span="16" v-if="this.siteList.length >= 2">
              <a-form-item label="站点名称" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
                <select-site @comMethods="changeSite" selectWidth="100%"/>
<!--                <a-select @change="changeSite"-->
<!--                          :defaultValue="siteCode"-->
<!--                          show-search-->
<!--                          :filter-option="filterOption"-->
<!--                          placeholder="请选择站点">-->
<!--                  <a-select-option v-for="site in siteList"-->
<!--                                   :key="site.id"-->
<!--                                   :value="site.code"-->
<!--                  >-->
<!--                    {{ site.name }}-->
<!--                  </a-select-option>-->
<!--                </a-select>-->
              </a-form-item>
            </a-col>
            <template v-if="siteCode !== undefined">
              <a-col :span="16">
                <a-form-item label="公司中文名称" :labelCol="labelCol" :wrapperCol="wrapperCol" hasFeedback>
                  <a-input id="companyCnName" v-decorator="['companyCnName',validatorRules.companyCnName]"
                           placeholder="请输入公司中文名称"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="16">
                <a-form-item label="公司英文名称" :labelCol="labelCol" :wrapperCol="wrapperCol" hasFeedback>
                  <a-input id="companyEnName" v-decorator="['companyEnName',validatorRules.companyEnName]"
                           placeholder="请输入公司英文名称"></a-input>
                </a-form-item>
              </a-col>
<!--              <a-col :span="16">-->
<!--                <a-form-item label="网站首页标题" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback-->
<!--                             extra="包含1个产品关键词，40-80个字符之内">-->
<!--                  <a-input v-decorator="['homepageTitle',validatorRules.homepageTitle]" placeholder="请输入网站首页标题"-->
<!--                           :maxLength=80></a-input>-->
<!--                </a-form-item>-->
<!--              </a-col>-->
              <a-col :span="16">
                <a-form-item label="企业LOGO" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <div slot="extra">
                    <div><a href="https://squoosh.app/" target="_blank">>>图片剪裁、压缩工具<<</a></div>
                    <div>1、限制图片格式：JPG,JPEG,PNG；</div>
                    <div>2、限制图片大小：不超过2MB</div>
                    <div>3、图片命名：'品牌名-logo'</div>
                  </div>
                  <a-upload
                    style="width: 20%;"
                    name="file"
                    list-type="picture-card"
                    :headers="headers"
                    :action="uploadAction"
                    :file-list="fileList"
                    :data="{biz:'public/material/' + this.siteCode + '/' +this.materialCode}"
                    :showUploadList="isMultiple"
                    :isMultiple="isMultiple"
                    :multiple="isMultiple"
                    @change="handleChange"
                    @preview="handlePreview"
                    :before-upload="beforeUpload"
                    v-decorator="['enterpriseLogo',validatorRules.enterpriseLogo]"
                  >
                    <img v-if="!isMultiple && picUrl" :src="getImgView(this.imageUrl)" style="width:100%;height:100%" />
                    <div v-else>
                      <a-icon :type="loading ? 'loading' : 'plus'" />
                      <div class="ant-upload-text">
                        上传
                      </div>
                    </div>
                    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
                      <img alt="example" style="width: 100%" :src="previewImage" />
                    </a-modal>
                  </a-upload>
                  <a-button v-if="imageUrl" icon="download" style="position: absolute;margin-top: 68px" type="primary"
                            ghost @click="downloadFile(imageUrl)">下载
                  </a-button>
                </a-form-item>
              </a-col>
              <a-col :span="16">
                <a-form-item label="联系人（英文）" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
                  <a-input v-decorator="['enterpriseContactName',validatorRules.enterpriseContactName]"
                           placeholder="请输入联系人（英文）"></a-input>
                </a-form-item>
              </a-col>

              <a-col :span="16">
                <a-form-item label="公司固定电话" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback
                             extra="如+86-514-88594521">
                  <a-input v-decorator="['enterpriseLandline',validatorRules.enterpriseLandline]"
                           placeholder="请输入公司固定电话"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="16">
                <a-form-item label="公司联系电话" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
                  <a-input v-decorator="['enterpriseContactPhone',{initialValue:''}]"
                           placeholder="请输入公司联系电话"></a-input>
                </a-form-item>
              </a-col>

              <a-col :span="16">
                <a-form-item label="公司电子邮箱" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
                  <a-input v-decorator="['enterpriseEmail',validatorRules.enterpriseEmail]"
                           placeholder="请输入公司电子邮箱"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="16">
                <a-form-item label="公司办公地址（英文）" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
                  <a-input v-decorator="['enterpriseOfficeAddress',validatorRules.enterpriseOfficeAddress]"
                           placeholder="请输入公司办公地址"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="16">
                <a-form-item label="公司品牌" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback
                             extra="填写真实注册商标，不可提供虚假内容，或冒用其他公司信息，以免网站侵权。">
                  <a-input v-decorator="['enterpriseBrand',validatorRules.enterpriseBrand]"
                           placeholder="请输入公司品牌"></a-input>
                </a-form-item>
              </a-col>

              <a-col :span="16">
                <a-form-item label="公司工厂地址（英文）" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input v-decorator="['enterpriseFactoryAddress',{initialValue:''}]"
                           placeholder="请输入公司工厂地址"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="16">
                <a-form-item label="公司工厂面积" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input addon-after="m²" v-decorator="['enterpriseFactoryArea',validatorRules.enterpriseFactoryArea]"
                           placeholder="请输入公司工厂面积"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="16">
                <a-form-item label="公司人数" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
                  <j-search-select-tag v-decorator="['employeeCount',validatorRules.employeeCount]" dict="adwebEmployeeCount"
                                       placeholder="请选择公司人数" />
                </a-form-item>
              </a-col>
              <a-col :span="16">
                <a-form-item label="研发人数或研发占比" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
                  <a-input v-decorator="['developerCount',validatorRules.developerCount]"
                           placeholder="请输入研发人数或研发占比"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="16">
                <a-form-item label="专利数量" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback extra="拥有的专利数量可以反映出企业创新能力,并因此更容易获得新的商业机会。">
                  <a-input v-decorator="['patentCount',validatorRules.patentCount]"
                           placeholder="请输入专利数量"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="16">
                <a-form-item label="服务客户数" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
                  <a-input v-decorator="['customerCount',validatorRules.customerCount]"
                           placeholder="服务客户数"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="16">
                <a-form-item label="资质与荣誉（英文）" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback extra="企业拥有资质和荣誉可以提升企业的信誉，使它更容易获得新的业务机会。">
                  <a-textarea v-decorator="['honorInfo',validatorRules.honorInfo]"
                              placeholder="请输入资质与荣誉（英文）" :autoSize="{ minRows: 10, maxRows: 20 }"
                              :maxLength="1000"></a-textarea>
                </a-form-item>
              </a-col>
              <a-col :span="16">
                <a-form-item label="公司概述（英文）" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
                  <a-textarea v-decorator="['enterpriseOverview',validatorRules.enterpriseOverview]"
                              placeholder="请输入公司概述（英文）" :autoSize="{ minRows: 10, maxRows: 20 }"
                              :maxLength="1000"></a-textarea>
                  <template slot="extra">
                    <div>1、用一段话概述公司性质、主营行业，以及主要产品等，且携带主营关键词，提升客户点击，文字会显示在网站首页描述中</div>
                    <div>2、最少200字，最多不超1000字</div>
                  </template>
                </a-form-item>
              </a-col>
              <a-col :span="16" style="text-align: center">
                <a-button @click="submitForm" type="primary">保 存</a-button>
              </a-col>
            </template>

          </a-row>
        </a-form>
        <a-empty v-else>
          <span slot="description">暂无站点</span>
        </a-empty>
      </a-spin>
    </a-card>
  </div>
</template>

<script>
import { getAction, getFileAccessHttpUrl, httpAction } from '/@/api/manage/manage'
import pick from 'lodash.pick'
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import selectSite from '@/components/adweb/selectSite'

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 {
  name: 'baseInfoForm',
  components: {
    selectSite
  },
  data() {
    return {
      form: this.$form.createForm(this),
      formSpinning: true,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      validatorRules: {
        siteCode: {
          rules: [
            { required: true, message: '请选择站点!' }
          ]
        },
        companyCnName: {
          initialValue: '',
          rules: [
            { required: true, message: '请输入公司中文名称!' }
            // { pattern: '^[a-zA-Z]+$', message: '英文名称格式不正确' }
          ]
        },
        companyEnName: {
          initialValue: '',
          rules: [
            { required: true, message: '请输入公司英文名称!' }
            // { pattern: '^[a-zA-Z]+$', message: '英文名称格式不正确' }
          ]
        },
        // homepageTitle: {
        //   initialValue: '',
        //   rules: [
        //     { required: true, message: '请输入网站首页标题!' },
        //     { min: 40, max: 80, message: '网站首页标题字数范围40~80', trigger: 'blur' }
        //   ]
        // },
        enterpriseLogo: {
          rules: [
            { required: true, message: '请上传企业LOGO!' }
          ]
        },
        enterpriseContactName: {
          initialValue: '',
          rules: [
            { required: true, message: '请输入公司联系人姓名!' }
          ]
        },
        enterpriseLandline: {
          initialValue: '',
          rules: [
            { required: true, message: '请输入公司固定电话!' }
            // { pattern: '^([0-9]{3,4}-)?[0-9]{7,8}$', message: '固定电话格式不正确' }
          ]
        },
        enterpriseFactoryArea:{
          initialValue: '',
          rules: [
            { required: true, message: '请输入公司工厂面积!' },
            { pattern: '^([1-9]\\d*|0)(\\.\\d{1,2})?$', message: '公司工厂面积格式不正确' }
          ]
        },
        developerCount:{
          initialValue: '',
          rules: [
            { required: true, message: '请输入研发人员数量或研发占比!' },
            { pattern: '^[0-9%/\\.]*$', message: '研发人员数量或研发占比格式不正确' }
          ]
        },
        patentCount:{
          initialValue: '',
          rules: [
            { required: true, message: '请输入专利数量!' },
            { pattern: '^[0-9]*$', message: '专利数量格式不正确' }
          ]
        },
        customerCount:{
          initialValue: '',
          rules: [
            { required: true, message: '请输入服务客户数!' },
            { pattern: '^[0-9]*$', message: '服务客户数格式不正确' }
          ]
        },
        enterpriseContactPhone: {
          initialValue: '',
          rules: [
            { required: false, message: '请输入公司联系电话!' },
            { pattern: '^1(3|4|5|7|8)\\d{9}$', message: '联系电话格式不正确' }
          ]
        },
        enterpriseEmail: {
          initialValue: '',
          rules: [
            { required: true, message: '请输入公司电子邮箱!' },
            { type: 'email', message: '邮箱格式不正确' }
          ]
        },
        enterpriseOfficeAddress: {
          initialValue: '',
          rules: [
            { required: true, message: '请输入公司办公地址!' }
          ]
        },
        enterpriseOverview: {
          initialValue: '',
          rules: [
            { required: true, message: '请输入公司概述!' },
            { min: 200, max: 1000, message: '公司概述字数范围200~1000', trigger: 'blur' }
          ]
        },
        employeeCount: {
          initialValue: '',
          rules: [
            { required: true, message: '请选择公司人数!' }
          ]
        },
        honorInfo: {
          initialValue: '',
          rules: [
            { required: true, message: '请输入资质与荣誉!' },
            { max: 1000, message: '资质与荣誉字数在1000以内', trigger: 'blur' }
          ]
        },
        enterpriseBrand: {
          initialValue: '',
          rules: [
            { required: true, message: '请输入公司品牌!' }
          ]
        }
      },
      model: {},
      url: {
        initUrl: '/adwebMaterial/list',
        add: '/adwebMaterial/commonAdd',
        edit: '/adwebMaterial/commonEdit',
        getMySiteUrl: '/adwebMaterial/getSiteByLoginUser'
      },
      siteList: [],
      siteCode: '',
      materialCode: 'baseInfo',
      headers: {
        'X-Access-Token': Vue.ls.get(ACCESS_TOKEN)
      },
      fileList: [],
      uploadAction: window._CONFIG['domianURL'] + '/sys/upload/uploadMinio',
      previewVisible: false,
      previewImage: '',
      loading: false,
      imageUrl: '',
      isMultiple: false,
      picUrl: false
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      let that = this
      getAction(this.url.getMySiteUrl).then(function(res) {
        if (res.code === 200 && res.result.length !== 0) {
          that.siteList = res.result
          let isInSite = false
          for (let i in res.result) {
            if (localStorage.getItem('siteCode') !== null && res.result[i].code === localStorage.getItem('siteCode')) {
              isInSite = true
            }
          }
          if (localStorage.getItem('siteCode') !== null && isInSite) {
            that.siteCode = localStorage.getItem('siteCode')
            that.initForm(localStorage.getItem('siteCode'))
          } else {
            that.siteCode = that.siteList[0].code
            localStorage.setItem('siteCode', that.siteList[0].code)
            that.initForm(that.siteList[0].code)
          }
        } else {
          that.formSpinning = false
          that.$message.error('您当前暂无站点！')
        }
      })
    },
    initForm(siteCode) {
      let that = this
      getAction(this.url.initUrl + '?siteCode=' + siteCode + '&materialCode=' + that.materialCode).then(function(res) {
        if (res.code === 200) {
          that.formSpinning = false
          that.model = Object.assign({}, res.result)
          if (res.result.enterpriseLogo != null) {
            that.picUrl = true
            that.imageUrl = res.result.enterpriseLogo
          } else {
            that.imageUrl = undefined
            that.picUrl = false
          }
          that.$nextTick(() => {
            that.form.setFieldsValue(pick(that.model,'honorInfo','customerCount','patentCount','developerCount','enterpriseFactoryArea','companyCnName', 'companyEnName', 'homepageTitle', 'enterpriseContactName', 'enterpriseLogo', 'enterpriseLandline',
              'enterpriseContactPhone', 'enterpriseEmail', 'enterpriseOfficeAddress', 'enterpriseFactoryAddress', 'enterpriseOverview', 'enterpriseBrand', 'employeeCount'))
          })
        } else {
          that.$message.error('网络错误！')
        }
      })
    },

    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },

    changeSite(value) {
      this.form.resetFields()
      this.siteCode = value
      // localStorage.setItem('siteCode', value)
      this.initForm(value)
    },

    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewVisible = true
      this.previewImage = file.url || file.preview
    },

    beforeUpload(file) {
      const index = file.name.indexOf('-logo')
      let isConfirm = true
      if (index <= 0) {
        isConfirm = false
        this.$message.error('上传失败，图片命名错误!')
      }
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/webp'
      if (!isJpgOrPng) {
        this.$message.error('上传失败，图片格式错误!')
      }
      const isLt100K = file.size / 1024 < 2048
      if (!isLt100K) {
        this.$message.error('上传失败，图片大小限制2MB!')
      }
      return isLt100K && isJpgOrPng && isConfirm
    },

    handleChange(info) {
      if (info.file.status === 'uploading') {
        this.fileList = info.fileList.slice(-1)
      } else if (info.file.status === 'done') {
        if (info.file.response.code !== 500) {
          this.$message.success(`${info.file.name} 文件上传成功！`)
          this.imageUrl = info.file.response.message
          this.picUrl = true
          this.fileList = info.fileList.slice(-1)
        } else {
          this.$message.error('上传失败，请刷新页面重试！')
        }
      } else if (info.file.status === 'removed') {
        this.$message.success(`${info.file.name} 文件删除成功！`)
        this.fileList = info.fileList.slice(-1)
      }
    },

    /* 图片预览 */
    getImgView(text) {
      if (text && text.indexOf(',') > 0) {
        text = text.substring(0, text.indexOf(','))
      }
      return getFileAccessHttpUrl(text)
    },

    downloadFile(text) {
      if (!text) {
        this.$message.warning('未知的文件')
        return
      }
      if (text.indexOf(',') > 0) {
        text = text.substring(0, text.indexOf(','))
      }
      let url = getFileAccessHttpUrl(text)
      window.open(url)
    },

    handleCancel() {
      this.previewVisible = false
    },

    submitForm() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          let httpurl = ''
          let method = ''
          if (!this.model.materialId) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          let formData = Object.assign(this.model, values)
          if (formData.employeeCount === undefined) {
            formData.employeeCount = ''
          }
          if (this.imageUrl === undefined) {
            formData.enterpriseLogo = null
          } else {
            formData.enterpriseLogo = this.imageUrl
          }
          formData.siteCode = that.siteCode
          formData.materialCode = that.materialCode
          httpAction(httpurl, formData, method).then((res) => {
            if (res.success) {
              that.$message.success(res.result)
              that.initForm(that.siteCode)
            } else {
              that.$message.warning(res.message)
            }
          })
        }
      })
    }
  }
}
</script>

<style>
.ant-form-extra {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.65);
  line-height: 2em;
}
</style>
