<template>
  <div>
    <el-dialog class="special-opt-dlg" :title="dialogTitle" @open="init" :visible.sync="isShow" width="690">
      <div class="dialog-body" v-loading="initLoading">
        <el-form ref="specialForm" :model="special" :rules="specialFormRules" label-width="110px" class="content-form">
          <el-row>
            <el-col :span="24">
              <el-form-item prop="title" :label="oprateName+'名称：'">
                <el-input :maxlength="100" @blur="specialTitleBlur" v-model="special.title"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <div v-show="titleCheckFlag">
                <span stype="color:red;">注意：已经存在相同标题</span>
              </div>
            </el-col>
          </el-row>
          <el-row v-if="pageType==='Special'">
            <el-col :span="24">
              <el-form-item prop="fileName" label="生成文件名：">
                <el-input :maxlength="100" v-model="special.fileName"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item prop="keywords" label="关键词：">
                <el-input-tags :tags="keywords" @change="keywordsChange" :limit="10"></el-input-tags>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item prop="summary" label="简介：">
                <el-input v-model="special.summary" :autosize="{minRows:2, maxRows:4}" :maxlength="1200" style="width:100%" type="textarea" :rows="2"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item prop="subjectID" :label="oprateName+'分类：'">
                <tree-select class="site-selector" width="100%" top :value.sync="special.subjectID" :items="subjectDatas" placeholder="请选择"></tree-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="styleID" :label="oprateName+'风格：'">
                <el-select style="width:100%" v-model="special.styleID" placeholder="请选择">
                  <el-option v-for="item in styleDatas" :key="item.ID" :label="item.name" :value="item.ID">{{item.name}}</el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="pageType==='Special'">
            <el-col :span="24">
              <el-form-item label="发布平台：">
                <el-checkbox-group @change="platformAttrChange" v-model="special.platformAttribute_JsonArray">
                  <el-checkbox v-for="platform in platformDatas" :key="platform.ID" :label="platform.ID">{{platform.name}}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item prop="logoFile" label="Logo图片：">
                <logo-path
                  :path.sync="special.logoFile"
                  @update:path="logoModified"
                  :resource-dialog-props="resourceDialogProps"
                ></logo-path>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShow = false">取 消</el-button>
        <el-button type="primary" :disabled="initLoading" :loading="confirmLoading" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import TreeSelect from '@src/components/TreeSelect.vue'
import LogoPath from '../contentcore/components/LogoPath.vue'
import util from '@src/common/util.js'
export default {
  name: 'SpecialDialog',
  props: {
    show: Boolean,
    ID: [Number, String],
    sourceID: [Number, String],
    dialogTitle: String,
    catalogId: [Number, String],
    pageType: String,
    fromEdit: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      initLoading: true,
      confirmLoading: false,
      titleCheckFlag: false,
      special: {
        title: '',
        fileName: '',
        logoFile: '',
        summary: '',
        subjectID: '',
        styleID: ''
      },
      subjectDatas: [],
      styleDatas: [],
      platformDatas: [],
      keywords: '',
      specialFormRules: {
        title: [{
          required: true,
          message: '请输入标题',
          trigger: 'blur'
        },
        {
          min: 1,
          max: 200,
          message: '长度在 1 到 200 个字符',
          trigger: 'blur'
        }
        ],
        fileName: [{
          required: true,
          message: '请输入文件名',
          trigger: 'blur'
        }, {
          type: 'string',
          message: '文件名只能包含英文字母、数字、横线或下划线',
          pattern: /^[-_\w]+$/,
          trigger: 'change'
        }],
        subjectID: [{
          required: true,
          message: '请选择模板分类',
          trigger: 'change'
        }],
        styleID: [{
          required: true,
          message: '请选择模板风格',
          trigger: 'change'
        }]
      },
      resourceDialogProps: {}
    }
  },
  computed: {
    isShow: {
      get() {
        return this.show
      },
      set(val) {
        this.$emit('update:show', val)
        this.$refs['specialForm'].resetFields()
      }
    },
    oprateName() {
      return this.pageType === 'Special' ? '专题' : '模板'
    }
  },
  methods: {
    async init() {
      this.initLoading = true
      let ajaxRes = await axios.get('/ui/pageweaver/forminit', {
        params: {
          sourceID: this.sourceID,
          ID: this.ID,
          pageType: this.pageType
        }
      })

      if (ajaxRes.data.status === 1) {
        const ajaxData = ajaxRes.data.data
        this.styleDatas = ajaxData.styles
        this.subjectDatas = ajaxData.subjects
        this.platformDatas = ajaxData.platforms
        this.special = ajaxData.special
        if (this.special.keywords === null) {
          this.special.keywords = ''
        }
        this.keywords = this.special.keywords
        this.special.pageType = this.pageType
        this.special.catalogID = this.catalogId
        if (!(this.ID || this.sourceID)) {
          this.special.subjectID = null
          this.special.styleID = null
        }
        // 根据模板创建需去掉加载到的ID值
        if (this.sourceID && this.sourceID !== 0) {
          this.special.ID = null
          this.special.sourceID = this.sourceID
        }
        if (this.special.styleID === 0) {
          this.special.styleID = null
        }
        if (this.pageType === 'Special') {
          if (this.special.platformAttribute_JsonArray.length === 0) {
            this.special.platformAttribute_JsonArray = [ 'pc' ]
            this.special.platformAttribute = "['pc']"
            this.special.platFormAttributeChange = true
          }
          this.special.Version = 3.0
          this.specialFormRules.fileName[0].required = true
          this.specialFormRules.subjectID[0].required = false
          this.specialFormRules.styleID[0].required = false
        } else {
          this.specialFormRules.fileName[0].required = false
          this.specialFormRules.subjectID[0].required = true
          this.specialFormRules.styleID[0].required = true
        }

        this.resourceDialogProps = {
          selectorURL: 'imageResources',
          resourceType: 'image',
          allowType: '.jpg,.jpeg,.png,gif,.bmp',
          height: 200,
          width: 200,
          catalogID: this.catalogId,
          url: ''
        }
      } else {
        util.showResponseMessage(ajaxRes.data)
      }
      this.initLoading = false
    },
    specialTitleBlur() {
      if (this.special && (this.special.fileName === null || this.special.fileName === '') && this.pageType === 'Special' && this.special.title !== '') {
        this.special.fileName = window.util.getSpell(this.special.title, true)
      }
    },
    platformAttrChange() {
      this.special.platFormAttributeChange = true
      this.special.platformAttribute = `${this.special.platformAttribute_JsonArray}`
    },
    keywordsChange(val) {
      this.special.keywords = val
    },
    logoModified(logoFile) {
      if (logoFile !== null && logoFile !== '') {
        this.special.uploadLogoFlag = 'Y'
      } else {
        this.special.uploadLogoFlag = 'N'
      }
    },
    async confirm() {
      this.$refs.specialForm.validate(async valid => {
        if (valid) {
          this.confirmLoading = true
          if (typeof this.special.uploadLogoFlag === 'undefined' || this.special.uploadLogoFlag === null) {
            this.special.uploadLogoFlag = 'N'
          }

          let includedFields = ['ID', 'title', 'styleID', 'subjectID', 'keywords', 'logoFile', 'summary']
          if (this.ID === null) {
            includedFields.push('sourceID')
          }
          const pickObj = {}
          for (let field in this.special) {
            let val = this.special[field]
            if ((_.isNumber(val) || !_.isEmpty(val)) && includedFields.includes(field)) {
              pickObj[field] = val
            }
          }
          const pageData = pickObj
          if (this.ID === null && !_.isEmpty(this.sourceID)) {
            pageData.sourceID = this.sourceID
          }

          const saveURL = this.pageType === 'Special' ? '/ui/specialv3' : '/ui/pageweaver/template'
          const resp = this.ID ? await axios.put(`${saveURL}/${this.ID}`, pageData) : await axios.post(`${saveURL}`, pageData)
          util.showResponseMessage(resp.data)
          this.confirmLoading = false
          if (resp.data.status === 1) {
            this.isShow = false
            this.$emit('callback', resp.data)
          }
        }
      })
    }
  },
  components: {
    'tree-select': TreeSelect,
    'logo-path': LogoPath
  }
}

</script>
<style scoped>
  .avatar{max-width: 120px;max-height:120px;}
</style>
