<template>
  <div class="app-warp">
    <div class="detail-structure">
      <el-page-header :content="parentObj.TYPE === 'add' ? '新增' : parentObj.TYPE === 'edit' ? '修改' : '查看'" @back="goBack"/>
      <div class="detail-container">
        <el-form ref="form" :model="form" :rules="rules" :disabled="parentObj.TYPE === 'view'" label-width="150px">
          <el-row>

            <el-col :span="12">
              <el-form-item label="机构名称" prop="CORP_NAME">
                <el-input v-model="form.CORP_NAME" placeholder="请输入机构名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属机构" prop="CORPINFO_ID">
                <el-select v-model="form.CORPINFO_ID" style="width: 100%;">
                  <el-option v-for="item in corpList" :key="item.CORPINFO_ID" :value="item.CORPINFO_ID" :label="item.NAME"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="有限期" prop="TIME">
                <el-date-picker
                  v-model="form.TIME"
                  style="width: 100%;"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="域名" prop="DOMAIN_NAME">
                <el-input v-model="form.DOMAIN_NAME" placeholder="域名"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="手机端域名" prop="APP_DOMAIN_NAME">
                <el-input v-model="form.APP_DOMAIN_NAME" placeholder="域名"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="最大企业数" prop="ENTERPRISE_MAXIMUM">
                <el-input v-model.number="form.ENTERPRISE_MAXIMUM" placeholder="请输入最大企业数" οninput="value=value.replace(/[^0-9]/g,'')" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="最大学员数" prop="STUDENT_MAXIMUM">
                <el-input v-model.number="form.STUDENT_MAXIMUM" placeholder="请输入最大学员数" οninput="value=value.replace(/[^0-9]/g,'')"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-col :span="4">
                <el-form-item label="企业logo" prop="file">
                  <el-upload
                    :on-preview="handlePreviewIdPhoto"
                    :on-remove="handleRemoveIdPhoto"
                    :on-change="handleChangeIdPhoto"
                    :auto-upload="false"
                    :file-list="form.file"
                    :limit="1"
                    :class="{hide:hideUpload}"
                    action="#"
                    accept=".jpg,.jpeg,.png"
                    list-type="picture-card">
                    <i class="el-icon-plus"/>
                  </el-upload>
                  <el-dialog :visible.sync="uploadVisible" append-to-body>
                    <img :src="CAPTURE" width="100%" alt="">
                  </el-dialog>
                </el-form-item>
              </el-col>
              <el-col :span="20">
                <div class="text-tip">
                  *请上传背景透明的png图片，<br>
                  建议尺寸为600px*600px。
                </div>
              </el-col>
            </el-col>
          </el-row>
        </el-form>
        <div class="detail_foot">
          <el-button v-if="parentObj.TYPE !== 'view'" type="primary" @click="confirm">保存</el-button>
          <el-button icon="el-icon-arrow-left" @click="goBack">取消</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { requestFN } from '@/utils/request'
import { upload } from '@/utils/upload'
export default {
  data() {
    var hasDomainName = (rule, value, callback) => {
      requestFN(
        '/oemmanage/hasDomainName',
        {
          DOMAIN_NAME: this.form.DOMAIN_NAME,
          OEM_MANAGE_ID: this.form.OEM_MANAGE_ID,
          tm: new Date().getTime()
        }
      ).then((data) => {
        if (data.result == 'success') {
          callback()
        } else {
          // console.info('用户名重复')
          callback(new Error('域名重复'))
        }
      }).catch((e) => {

      })
    }
    var hasAppDomainName = (rule, value, callback) => {
      requestFN(
        '/oemmanage/hasAppDomainName',
        {
          APP_DOMAIN_NAME: this.form.APP_DOMAIN_NAME,
          OEM_MANAGE_ID: this.form.OEM_MANAGE_ID,
          tm: new Date().getTime()
        }
      ).then((data) => {
        if (data.result == 'success') {
          callback()
        } else {
          // console.info('用户名重复')
          callback(new Error('域名重复'))
        }
      }).catch((e) => {

      })
    }
    return {
      config: config,
      form: {
        CORP_NAME: '',
        DOMAIN_NAME: '',
        APP_DOMAIN_NAME: '',
        START_TIME: '',
        END_TIME: '',
        TIME: [],
        ENTERPRISE_MAXIMUM: '',
        STUDENT_MAXIMUM: '',
        CORPINFO_ID: '',
        file: []
      },
      rules: {
        CORP_NAME: [
          { required: true, message: '请输入机构名称', trigger: 'blur' }
        ],
        CORPINFO_ID: [
          { required: true, message: '请选择所属机构', trigger: 'blur' }
        ],
        DOMAIN_NAME: [
          { required: true, message: '请输入域名', trigger: 'blur' },
          { validator: hasDomainName, trigger: 'blur' }
        ],
        APP_DOMAIN_NAME: [
          { required: true, message: '请输入APP域名', trigger: 'blur' },
          { validator: hasAppDomainName, trigger: 'blur' }
        ],
        TIME: [
          { required: true, message: '请选择有效期', trigger: 'blur' }
        ],
        ENTERPRISE_MAXIMUM: [
          { required: true, message: '请输入最大企业数', trigger: 'blur' }
        ],
        STUDENT_MAXIMUM: [
          { required: true, message: '请输入最大学员数', trigger: 'blur' }
        ],
        file: [
          { required: true, message: '请上传手机端logo', trigger: 'blur' }
        ]
      },
      corpList: [],
      hideUpload: false,
      uploadVisible: false,
      CAPTURE: ''
    }
  },
  inject: ['setActiveName', 'parentObj'],
  created() {
    if (this.parentObj.OEM_MANAGE_ID) {
      this.getData()
    }
    this.getCorpList()
  },
  methods: {
    getData() {
      requestFN('/oemmanage/goEdit', {
        OEM_MANAGE_ID: this.parentObj.OEM_MANAGE_ID
      }).then((data) => {
        if (data.pd.START_TIME && data.pd.END_TIME) {
          data.pd.TIME = [data.pd.START_TIME, data.pd.END_TIME]
        }
        if (data.pd.APP_LOGO_PATH) {
          data.pd.file = [{
            url: config.fileUrl + data.pd.APP_LOGO_PATH
          }]
          this.hideUpload = true
        } else {
          data.pd.file = []
        }
        this.form = data.pd
      })
    },
    getCorpList() {
      requestFN('/corpinfo/listAll', {
      }).then((data) => {
        this.corpList = data.corpList
      })
    },
    handlePreviewIdPhoto(file) {
      this.CAPTURE = file.url
      this.uploadVisible = true
    },
    handleRemoveIdPhoto(file, fileList) {
      this.form.file = fileList
      this.hideUpload = fileList.length >= 1
    },
    handleChangeIdPhoto(file, fileList) {
      const types = ['image/jpeg', 'image/jpg', 'image/png']
      const isImage = types.includes(file.raw.type)
      if (!isImage) {
        this.$message.error('上传图片只能是 JPG、JPEG、PNG 格式!')
        fileList.pop()
      }
      const img = new Image()
      img.src = file.url
      img.onload = () => {
        if (img.width !== img.height) {
          this.$message.warning('请上传正方形图片！')
          fileList.pop()
          return
        } else {
          this.form.file = fileList
          this.hideUpload = fileList.length >= 1
        }
      }
    },
    confirm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const formData = new FormData()
          Object.keys(this.form).map(key => {
            formData.append(key, this.form[key])
          })
          formData.append('START_TIME', this.form.TIME[0])
          formData.append('END_TIME', this.form.TIME[1])
          if (this.form.file[0].raw) {
            formData.append('APP_LOGO', this.form.file[0].raw)
          }
          upload('/oemmanage/' + this.parentObj.TYPE, formData).then((res) => {
            if (res.errorMessage) {
              this.$message({
                message: res.errorMessage,
                type: 'warning'
              })
            } else {
              this.$message({
                message: '操作成功',
                type: 'success'
              })
              this.goBack()
            }
          })
        } else {
          this.$message.error('请检查输入项')
        }
      })
    },
    goBack() {
      this.setActiveName('List')
    }
  }
}
</script>

<style scoped>

</style>
