<template>
  <!-- 表单渲染 -->
  <el-dialog append-to-body :close-on-click-modal="false" :before-close="cancelView" :visible="visible" :title="title" width="1080px">
    <img v-if="stampImgSrc[0]" :src="stampImgSrc[0]" class="stamp-review">
    <img v-if="stampImgSrc[1]" :src="stampImgSrc[1]" class="stamp-review" style="top:50%">
    <el-form ref="formViewRef" :model="formData" :rules="rules" :status-icon="true" label-width="240px">
      <el-form-item label="供应商名称：" class="form-cell" prop="enterpriseName">
        <div class="cell-box">
          <el-autocomplete
            v-model="formData.enterpriseName"
            disabled
            class="cell-input"
            :fetch-suggestions="querySearch"
            placeholder="请输入供应商名称"
            :trigger-on-focus="false"
            @select="handleSelect"
          />
        </div>
      </el-form-item>
      <el-form-item label="品级标识设置：" class="form-cell" prop="rank">
        <div class="cell-box">
          <el-select v-model="formData.rank" disabled placeholder="产品小类" style="width: 160px">
            <el-option v-for="item in dict.product_rank" :key="item.id" :label="item.label" :value="item.value" />
          </el-select>
        </div>
      </el-form-item>
      <el-form-item label="产品名称：" class="form-cell" prop="productName">
        <div class="cell-box">
          <el-input v-model="formData.productName" disabled placeholder="请输入产品名称" class="cell-input" />
        </div>
      </el-form-item>
      <el-form-item label="产品分类：" class="form-cell" style="margin: 0">
        <div class="cell-box" style="display: flex">
          <el-form-item prop="productType">
            <el-select v-model="formData.productType" disabled placeholder="产品大类" style="width: 120px" @change="changeProductType">
              <el-option v-for="item in dict.product_type" :key="item.id" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item prop="productSubType" style="margin-left: 5px">
            <el-select v-model="formData.productSubType" disabled placeholder="产品小类" style="width: 160px">
              <el-option v-for="item in productSubTypeOpts" :key="item.id" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </div>
      </el-form-item>
      <el-form-item v-if="formData.productType&&formData.productType<5" label="产品属性：" class="form-cell">
        <div class="cell-box" style="max-width: 600px">
          <el-row>
            <el-col :span="5" class="grid-content">
              <div class="grid-label">品牌</div>
            </el-col>
            <el-col :span="7" class="grid-content">
              <el-input v-model="formData.attributeBrand" disabled placeholder="品牌" />
            </el-col>
            <el-col :span="5" class="grid-content">
              <div class="grid-label">消耗电流</div>
            </el-col>
            <el-col :span="7" class="grid-content">
              <el-input v-model="formData.attributeConsumptionCurrent" disabled placeholder="消耗电流" />
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="5" class="grid-content">
              <div class="grid-label">批号</div>
            </el-col>
            <el-col :span="7" class="grid-content">
              <el-input v-model="formData.attributeBatchNumber" disabled placeholder="批号" />
            </el-col>
            <el-col :span="5" class="grid-content">
              <div class="grid-label">额定功率</div>
            </el-col>
            <el-col :span="7" class="grid-content">
              <el-input v-model="formData.attributeRatedPower" disabled placeholder="额定功率" />
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="5" class="grid-content">
              <div class="grid-label">型号</div>
            </el-col>
            <el-col :span="7" class="grid-content">
              <el-input v-model="formData.attributeModel" disabled placeholder="型号" />
            </el-col>
            <el-col :span="5" class="grid-content">
              <div class="grid-label">反应时间</div>
            </el-col>
            <el-col :span="7" class="grid-content">
              <el-input v-model="formData.attributeReactionTime" disabled placeholder="反应时间" />
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="5" class="grid-content">
              <div class="grid-label">工作电压</div>
            </el-col>
            <el-col :span="7" class="grid-content">
              <el-input v-model="formData.attributeWorkingVoltage" disabled placeholder="工作电压" />
            </el-col>
            <el-col :span="5" class="grid-content">
              <div class="grid-label">封装</div>
            </el-col>
            <el-col :span="7" class="grid-content">
              <el-input v-model="formData.attributeEncapsulation" disabled placeholder="封装" />
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="5" class="grid-content">
              <div class="grid-label">质量保证</div>
            </el-col>
            <el-col :span="7" class="grid-content">
              <el-input v-model="formData.attributeQualityAssurance" disabled placeholder="质量保证" />
            </el-col>
            <el-col :span="5" class="grid-content">
              <div class="grid-label">产地</div>
            </el-col>
            <el-col :span="7" class="grid-content">
              <el-input v-model="formData.attributeProducingArea" disabled placeholder="产地" />
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="5" class="grid-content">
              <div class="grid-label">数量</div>
            </el-col>
            <el-col :span="7" class="grid-content">
              <el-input v-model="formData.attributeNumber" disabled placeholder="数量" />
            </el-col>
            <el-col :span="5" class="grid-content">
              <div class="grid-label">颜色</div>
            </el-col>
            <el-col :span="7" class="grid-content">
              <el-input v-model="formData.attributeColor" disabled placeholder="颜色" />
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="5" class="grid-content">
              <div class="grid-label">适用场景</div>
            </el-col>
            <el-col :span="19" class="grid-content">
              <el-input v-model="formData.attributeApplicableScenarios" disabled placeholder="适用场景" />
            </el-col>
          </el-row>
        </div>
      </el-form-item>
      <el-form-item label="产品价格区间（元）：" class="form-cell" style="margin: 0">
        <div class="cell-box" style="display: flex">
          <div class="cell-textarea">{{ formData.minPrice }} ~ {{ formData.maxPrice }}</div>
        </div>
      </el-form-item>
      <el-form-item label="产品特点：" class="form-cell" prop="productFeature">
        <div class="cell-box">
          <el-tag
            v-for="tag in productFeature"
            :key="tag"
            size="small"
            :type="tagTypes[formData.productType||0]"
            :disable-transitions="false"
            @close="handleClose(tag)"
          >
            {{ tag }}
          </el-tag>
        </div>
      </el-form-item>
      <el-form-item label="产品照片：" class="form-cell" prop="productPic">
        <div class="cell-box">
          <ul class="el-upload-list el-upload-list--picture-card" style="float: left">
            <li v-for="(item, index) in imgList" :key="index" tabindex="0" class="el-upload-list__item is-success">
              <img :src="imgSrcStart+'/productPic/'+item" class="el-upload-list__item-thumbnail">
              <label class="el-upload-list__item-status-label"><i class="el-icon-upload-success el-icon-check" /></label>
              <span class="el-upload-list__item-actions">
                <span class="el-upload-list__item-preview" @click="dialogImgUrl=item;dialogImgVisible=true"><i class="el-icon-zoom-in" /></span>
              </span>
            </li>
          </ul>
          <el-dialog append-to-body :visible.sync="dialogImgVisible">
            <img width="100%" :src="imgSrcStart+'/productPic/'+dialogImgUrl">
          </el-dialog>
        </div>
      </el-form-item>
      <el-form-item label="产品概述：" class="form-cell" prop="productDescribe">
        <div class="cell-box">
          <div v-html="formData.productDescribe" />
        </div>
      </el-form-item>
      <el-form-item label="其他说明：" class="form-cell" prop="notes">
        <div class="cell-box">
          <div class="cell-textarea">{{ formData.notes }}</div>
        </div>
      </el-form-item>
      <el-form-item label="交易保障承诺：" class="form-cell" prop="letterOfCommitment">
        <div class="cell-box">
          <el-checkbox v-model="formData.letterOfCommitment" disabled><em>卖家承诺履约合规诈骗包赔，保障产品交易安全</em></el-checkbox>
        </div>
      </el-form-item>
      <el-form-item v-if="!isReview && formData.reviewComments" label="审核意见：" class="form-cell">
        <div class="cell-box">
          <div class="cell-textarea">{{ formData.reviewComments }}</div>
        </div>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: center">
      <el-button @click="cancelView">关闭</el-button>
      <el-button v-if="isReview" type="primary" @click="submitForm(true)">通过</el-button>
      <el-button v-if="isReview" type="primary" @click="reviewVisible=true">驳回</el-button>
    </div>
    <el-dialog append-to-body :close-on-click-modal="false" :before-close="cancelReview" :visible="reviewVisible" title="审核意见" width="600px">
      <el-form ref="formReviewRef" :model="formReview" :rules="rules" :status-icon="true" label-width="120px">
        <el-form-item label="审核意见：" class="form-cell" prop="reviewComments">
          <div class="cell-box">
            <el-input v-model="formReview.reviewComments" type="textarea" placeholder="请输入审核意见" maxlength="100" :autosize="{ minRows: 4, maxRows: 6}" show-word-limit resize="none" style="width: 300px" />
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="submitForm(false)">提交</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>
<script>
import { getToken } from '@/utils/auth'
import { HttpReq } from '@/api/common'
import { mapGetters } from 'vuex'
import review_pass from '@/assets/images/review_pass.png'
import review_await from '@/assets/images/review_await.png'
import review_failed from '@/assets/images/review_failed.png'
import pd from '@/assets/images/pd.png'
import pu from '@/assets/images/pu.png'

export default {
  dicts: ['product_rank', 'product_type', 'product_type_1', 'product_type_2', 'product_type_3', 'product_type_4', 'product_type_5', 'product_type_6', 'product_type_7'],
  data() {
    const checkPrice = (rule, value, callback) => {
      if (!value) {
        return callback()
      }
      if (!Number.isInteger(value)) {
        return callback(new Error('请输入数字值'))
      }
      setTimeout(() => {
        if (this.formData.minPrice && value < this.formData.minPrice) {
          return callback(new Error('区间值错误'))
        }
        if (this.formData.maxPrice && value > this.formData.maxPrice) {
          return callback(new Error('区间值错误'))
        }
        return callback()
      }, 500)
    }
    return {
      uploadHeaders: { 'Authorization': getToken() },
      stampImgSrc: ['', ''],
      isReview: false,
      imgSrcStart: process.env.VUE_APP_BASE_API,
      editor: false, // 富文本对象
      dialogImageUrl: '',
      dialogImageVisible: false,
      imgList: [],
      dialogImgUrl: '',
      dialogImgVisible: false,
      visible: false,
      tagTypes: ['', 'primary', 'success', 'warning', 'danger', 'info', 'info', 'info'],
      title: '编辑产品信息详情',
      productSubTypeOpts: [],
      inputVisible: false,
      inputValue: '',
      productFeature: [], // 产品特点tag列表
      formData: {
        productId: null,
        customerId: null, // 供应商id
        enterpriseName: '', // 供应商名称
        productName: '', // 产品名称
        productType: '1', // 产品大类
        productSubType: null, // 产品小类
        minPrice: null, // 价格区间-小
        maxPrice: null, // 价格区间-大
        productFeature: null, // 产品特点
        productPic: '', // 产品图片
        productDescribe: '', // 产品描述（富文本）
        notes: null, // 其他说明
        letterOfCommitment: false, // 交易保障承诺
        attributeBrand: '', // 属性-品牌
        attributeConsumptionCurrent: '', // 属性-消耗电流
        attributeProductName: '', // 属性-产品名称
        attributeRatedPower: '', // 属性-额定功率
        attributeModel: '', // 属性-型号
        attributeReactionTime: '', // 属性-反应时间
        attributeWorkingVoltage: '', // 属性-工作电压
        attributeEncapsulation: '', // 属性-封装
        attributeQualityAssurance: '', // 属性-质量保证
        attributeProducingArea: '', // 属性-产地
        attributeNumber: '', // 属性-数量
        attributeColor: '', // 属性-颜色
        attributeApplicableScenarios: '', // 属性-适用场景
        attributeBatchNumber: '', // 属性-批号
        rank: '1' // 产品品级
      },
      reviewVisible: false,
      formReview: {
        reviewComments: ''
      },
      rules: {
        reviewComments: { required: true, message: '请填写审核意见', trigger: 'blur' }
      }
    }
  },
  computed: {
    ...mapGetters([
      'imagesUploadApi',
      'baseApi'
    ])
  },
  mounted() {
    this.productSubTypeOpts = this.dict['product_type_1']
  },
  methods: {
    checkEnterpriseName(rule, value, callback) {
      this.$nextTick(_ => {
        HttpReq.backstageApi.checkEnterpriseName({
          name: value, id: this.formData.customerId
        }).then((res) => {
          if (res.data) {
            callback()
          } else {
            callback(new Error(res.msg))
          }
        })
      })
    },
    querySearch(queryString, cb) {
      HttpReq.backstageApi.associateQueryEnterpriseName({
        name: queryString
      }).then((res) => {
        cb(res.data)
      })
    },
    handleSelect(item) {
      this.formData.customerId = item.id
      this.$refs.formViewRef.validateField('enterpriseName', valid => {
        return valid
      })
    },
    handleClose(tag) {
      this.productFeature.splice(this.productFeature.indexOf(tag), 1)
      this.formData.productFeature = this.productFeature.join(';')
    },
    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue && !this.productFeature.filter(item => { return item === inputValue }).length) {
        this.productFeature.push(inputValue)
        this.formData.productFeature = this.productFeature.join(';')
      }
      this.inputValue = ''
      this.inputVisible = false
    },
    handleExceed() {
      this.$message({
        message: '超出最大上传数量限制',
        type: 'info'
      })
    },
    handleRemoveImg(item) {
      this.imgList.splice(this.imgList.indexOf(item), 1)
      const arr = this.formData.productPic.split(';')
      arr.splice(arr.indexOf(item), 1)
      this.formData.productPic = arr.join(';')
    },
    handleRemove(file, fileList) {
      HttpReq.backstageApi.deleteProductPic({
        productPic: file.response.productPic
      }).then((res) => {
        this.$notify({
          title: res.msg,
          type: 'success',
          duration: 2500
        })
        const arr = []
        fileList.forEach(item => {
          arr.push(item.response.productPic)
        })
        this.formData.productPic = arr.join(';')
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogImageVisible = true
    },
    handleImported(response, file, fileList) {
      this.$nextTick(() => {
        const arr = this.formData.productPic ? this.formData.productPic.split(';') : []
        arr.push(response.productPic)
        this.formData.productPic = arr.join(';')
        this.$notify({
          title: '上传成功！',
          type: 'success',
          duration: 2500
        })
      })
    },
    showView() {
      this.visible = true
    },
    hideView() {
      this.$refs.formViewRef.resetFields()
      this.productSubTypeOpts = this.dict['product_type_1']
      this.productFeature = []
      this.visible = false
    },
    cancelView() {
      this.cancelReview()
      this.hideView()
      this.stampImgSrc = ['', '']
    },
    cancelReview() {
      if (this.$refs.formReviewRef) {
        this.$refs.formReviewRef.resetFields()
      }
      this.formReview.reviewComments = ''
      this.reviewVisible = false
    },
    submitForm(isPass) {
      if (isPass) {
        this.formReview.reviewComments = '审核通过'
        HttpReq.backstageApi.reviewProduct({
          productId: this.formData.productId,
          reviewComments: this.formReview.reviewComments,
          type: 1
        }).then((res) => {
          this.$notify({
            title: res.msg,
            type: 'success',
            duration: 2500
          })
          if (res.code === 200) {
            this.cancelView()
            this.$parent.loadData()
          }
        })
        return
      }
      this.$refs.formReviewRef.validate((valid, obj) => {
        if (valid) {
          HttpReq.backstageApi.reviewProduct({
            productId: this.formData.productId,
            reviewComments: this.formReview.reviewComments,
            type: 0
          }).then((res) => {
            this.$notify({
              title: res.msg,
              type: 'success',
              duration: 2500
            })
            if (res.code === 200) {
              this.cancelView()
              this.$parent.loadData()
            }
          })
        } else {
          this.$message({
            message: '表单信息有误，请核对无误后提交！',
            type: 'error'
          })
        }
      })
    },
    changeProductType() {
      this.formData.productSubType = null
      this.productSubTypeOpts = this.dict['product_type_' + this.formData.productType]
    },
    loadData(productId, isReview) {
      this.isReview = isReview
      this.title = `${isReview ? '审核' : '查看'}产品信息详情`
      this.showView()
      this.$nextTick(() => {
        // 初始化数据
        HttpReq.backstageApi.queryProductDetail({ productId }).then((res) => {
          if (res.code === 200) {
            this.formData = Object.assign(this.formData, res.data)
            if (this.formData.productPic) {
              this.imgList = this.formData.productPic.split(';')
            }
            if (this.formData.productType) {
              this.productSubTypeOpts = this.dict['product_type_' + this.formData.productType]
            }
            if (this.formData.productFeature) {
              this.productFeature = this.formData.productFeature.split(';')
            }
            switch (this.formData.status) {
              case '2': this.stampImgSrc[0] = review_failed
                break
              case '3': this.stampImgSrc[0] = review_await
                break
              case '4': this.stampImgSrc[0] = review_pass
                break
              case '5':
                this.stampImgSrc[0] = review_pass
                this.stampImgSrc[1] = pu
                break
              case '6':
                this.stampImgSrc[0] = ''
                this.stampImgSrc[1] = pd
                break
              default:
                this.stampImgSrc[0] = ''
                this.stampImgSrc[1] = ''
            }
          } else {
            this.$message({
              message: res.msg,
              type: 'error'
            })
          }
        })
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.stamp-review {
  border-style: none;
  position: absolute;
  right: 15%;
  top: 40%;
  z-index: 99;
}
.grid-content {
  border: 1px solid rgba(100, 100, 100, 0.3);
  padding: 0;
}
.grid-label {
  background: #dedede;
  padding: 0 10px;
}
.editor{
  text-align:left;
  width: 680px;
}
.cell-textarea {
  min-height: 50px;
  color: #777;
  font-style: oblique;
  font-size: 14px;
  text-decoration: underline; //下划线
  text-underline-offset: 5px; //下划线和文字间距
  text-decoration-color: rgba(100, 100, 100, 0.4);
}
::v-deep .w-e-text-container {
  height: 560px !important;
}
.cell-box {
  min-width: 120px;
  .cell-input {
    width: 420px;
  }
  .cell-select {
    width: 220px;
  }
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 28px;
    line-height: 24px;
    padding: 0 8px;
  }
  .input-new-tag {
    width: 140px;
    height: 28px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  >>>.el-input__inner {
    border: 1px solid rgba(100, 100, 100, 0.1);
    border-bottom: 1px solid rgba(100, 100, 100, 0.2);
    border-radius: 5px;
  }
  >>>.el-input.is-disabled .el-input__inner {
    border-radius: 0;
    border: 0;
    border-bottom: 1px solid rgba(100, 100, 100, 0.4);
    background: white;
    color: #777;
    font-style: oblique;
    font-size: 14px;
    cursor: text;
  }
  >>>.el-input.is-disabled .el-input__icon {
    cursor: text;
  }
  >>>.el-icon-circle-check {
    color: #13ce66;
  }
  >>>.el-icon-arrow-up:before {
    content: '';
  }
}
</style>
