<!--平台玩具和待核对玩具公用-->
<template>
  <div>
    <div class="info-header"><p class="info-title">基础信息</p></div>
    <el-divider class="mini-divider-table" />
    <el-form ref="form" class="standard-form" :model="localFormState" :rules="rules" size="mini" label-width="100px">
      <el-form-item label="玩具名称" prop="toyName">
        <el-input v-model.trim="localFormState.toyName" clearable placeholder="请输入玩具名称" />
      </el-form-item>
      <el-form-item label="玩具图片" style="width: 100%">
        <upload-toy-img :file-list.sync="localFileList" :form-state.sync="localFormState" />
      </el-form-item>
      <el-form-item
        label="计数单位"
        prop="toyUnit"
        style="line-height: 28px"
        :rules="{ required: localFormState.toyStatus !== '1', message: '计数单位不能为空', trigger: ['change', 'blur'] }"
      >
        <el-radio-group v-model="localFormState.toyUnit">
          <el-radio v-for="dict in dict.type[DictType.toy_unit]" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="品牌">
        <select-toy-brand v-model="localFormState.toyBrandId" />
      </el-form-item>
    </el-form>
    <template v-if="showPosition">
      <div class="info-header mt20"><p class="info-title">投放信息</p></div>
      <el-divider class="mini-divider-table" />
      <advertise-info :advertisting-dtos="formState.advertistingDtos" />
    </template>
    <div class="info-header mt20"><p class="info-title">{{ !!localFormState.toyStatus || ($route.query.type ==='add') ? '分类信息' : '核对信息' }}</p></div>
    <el-divider class="mini-divider-table" />
    <category-card-form
      ref="categoryFormRef"
      :container-style="containerStyle"
      :show-card-header="showCardHeader"
      :form-item-required="requiredItem"
      :form-state="localFormState"
      :no-data="noData"
      @refresh="$emit('refresh')"
    />
    <div class="info-header mt20"><p class="info-title">玩具描述</p></div>
    <el-divider class="mini-divider-table" />
    <editor v-model="localFormState.toyDescription" :min-height="192" :style="containerStyle" />
    <slot />
  </div>
</template>
<script>
import SelectToyBrand from '@/components/Select/SelectToyBrand.vue'
import UploadToyImg from '@/components/Upload/UploadToyImg.vue'
import options from '@/utils/dict/options'
import { compressImg, urlToBase64ToFile } from '@/utils'
import DictType from '@/utils/dict/DictType'
import { uploadFile } from '@/api/upload'
import { removeFile } from '@/api/file'
import CategoryCardForm from '@/views/toy/components/CategoryCardForm.vue'
import AdvertiseInfo from '@/components/ToyInfo/advertiseInfo.vue'

const toyReleaseClassOptions = options.toyReleaseClass

export default {
  name: 'EditBasic',
  dicts: ['toy_unit'],
  components: {
    AdvertiseInfo,
    SelectToyBrand,
    UploadToyImg,
    CategoryCardForm
  },
  props: {
    formState: {
      type: Object,
      default: () => {
      }
    },
    validateCategory: {
      type: Boolean,
      default: false
    },
    fileList: {
      type: Array,
      default: () => []
    },
    showPosition: {
      type: Boolean,
      default: false
    },
    containerStyle: {
      type: Object,
      default: () => {}
    },
    noData: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      options,
      DictType,
      toyReleaseClassOptions,
      uploadFileList: [], // 上传的图片
      loading: false,
      type: '',
      trimDisabled: false,
      rules: {
        toyName: [
          { required: true, message: '玩具名称不能为空', trigger: 'blur' },
          { max: 16, message: '玩具名称长度不能超过16位', trigger: 'blur' }
        ]
        // releaseClassArr: [{ required: true, message: '建议投放不能为空', trigger: 'blur' }],
        // fileId: [
        //   { required: true, message: '玩具图片不能为空', trigger: ['blur', 'change'] },
        //   { validator: this.fileIdValidator, trigger: ['blur', 'change'] }
        // ],
        // toyUnit: [{ required: true, message: '计数单位不能为空', trigger: 'blur' }]
      }
    }
  },
  computed: {
    localFormState() {
      return this.formState
    },
    localFileList: {
      get() {
        return this.fileList
      },
      set(val) {
        this.$emit('update:fileList', val)
      }
    },
    // 待审核完善玩具 和 平台玩具 显示状态校验
    requiredItem() {
      return this.localFormState.improvedType === '1' || this.localFormState.toyStatus === '0'
    },
    showCardHeader() {
      return this.formState.toyCateList.some(item => item.areaId)
    }
  },
  watch: {
    // localFileList: {
    //   handler(val) {
    //     if (val.length > 0) {
    //       this.$refs.form.clearValidate('fileId')
    //     }
    //   },
    //   deep: true,
    //   immediate: true
    // },
    'localFormState.improvedType': {
      handler(val) {
        if (val == '2') {
          this.$refs.form.clearValidate(['releaseClassArr', 'fileId', 'toyUnit'])
          this.localFormState.toyCateList.forEach((item, index) => {
            this.$refs.form.clearValidate(`toyCateList.${index}`)
          })
        }
      }
      // immediate: true
    },
    'localFormState.toyStatus': {
      handler(val) {
        if (val == '1') {
          this.$refs.form.clearValidate(['releaseClassArr', 'fileId', 'toyUnit'])
          this.localFormState.toyCateList.forEach((item, index) => {
            this.$refs.form.clearValidate(`toyCateList.${index}`)
          })
        }
      }
      // immediate: true
    }
  },
  methods: {
    onClearToycategory() {
      this.$refs.categoryFormRef.onClearValidateOfClass()
    },
    async uploadCoverImg(file) {
      const res = await compressImg(file, null, 30)
      const formData = new FormData()
      formData.append('file', res.file)
      const { data } = await uploadFile(formData)
      return data.fileUrl
    },
    changeType(val) {
      this.type = val
    },
    onSubmit() {
      return new Promise((resolve, reject) => {
        Promise.all([this.$refs.form.validate(), this.$refs.categoryFormRef.onSubmit()]).then(async(result) => {
          const valid = result.every(v => v)
          let values = {}
          if (valid) {
            const form = JSON.parse(JSON.stringify(this.localFormState))
            // 删除之前已存在的缩略图
            if (this.localFormState.kindergartenToyCompressedUrl) {
              removeFile([{ fileUrl: this.localFormState.kindergartenToyCompressedUrl }]).then()
            }
            const coverImg = this.localFileList.find(item => item.isPrimary)
            if (coverImg) {
              if (coverImg.uploadFile) {
                this.localFormState.kindergartenToyCompressedUrl = await this.uploadCoverImg(coverImg.uploadFile)
              } else {
                // url转file压缩文件 上传
                const coverFile = await urlToBase64ToFile(coverImg.url)
                this.localFormState.kindergartenToyCompressedUrl = await this.uploadCoverImg(coverFile)
              }
            } else {
              this.localFormState.kindergartenToyCompressedUrl = null
            }
            const { toyCateList, fileId } = form
            const temp = {
              toySortRelationList: toyCateList && toyCateList.length > 0 ? toyCateList.map((cate, index) => ({
                ...cate,
                ...cate.cate_,
                sortLevel: index + 1,
                releaseClassAge: cate.releaseClassArr.join(','),
                isRelation: '0',
                relationId: null,
                locationId: cate.locationId
              })) : [],
              fileId: fileId || null
            }
            values = Object.assign({}, JSON.parse(JSON.stringify(this.localFormState)), temp)
          }
          resolve({
            valid,
            values
          })
        }).catch((error) => {
          console.log(error)
          reject(error)
        })
      })
    }
  }
}
</script>

<style scoped lang="scss">
.category-flex {
  display: flex;
  //align-items: flex-start;
}

.category-wrapper {
  ::v-deep .el-form-item {
    margin-right: 10px;
  }

  //width: calc(100% - 86px);
}

::v-deep .category-options {
  width: 64px;
  text-align: center;

  &>span {
    height: 24px;

    .el-popover__reference-wrapper {
      width: 24px;
      height: 24px;

      &>i {
        margin: unset
      }
    }
  }
}

.cover-image {
  width: 90px;
  height: 90px;
  border-radius: 4px;
}
</style>
