<script>
import axios from "axios";
import {rCode} from "../map/rcodeMap_esm";
import {handle} from "../until/handle";
import InputRow from "./public/form/inputRow.vue";
import RoundedTitle from "./public/roundedTitle.vue";
import dbField_esm, {db_base} from "../map/dbField_esm";
import {FormVerify} from "kind-form-verify";
import {fieldCheck} from "../until/form/fieldVerify";
import Pop from "./public/pop.vue";
import PopCard from "./public/popCard.vue";
import ImageTable from "./public/imageTable.vue";
import {urlAddParam} from "@/until/url";

const emptyType = {
  type_name: '',
  type_logo: '',
  type_sort: 0,
  type_key: ''
}
let formVerify = null;
export default {
  name: 'typeEdit',
  components: {ImageTable, PopCard, Pop, RoundedTitle, InputRow},
  props: {
  },
  data () {
    return {
      isInitialized: false,
      title: '编辑类型',
      typeId: '',
      formType: {
        type_name: {
          val: "",
          oldVal: "",
          init: "",
          msg: "",
          state: 0,
        },
        type_logo: {
          val: '',
          init: '',
          msg: '',
          reCheckField: 'fileData',
          state: 0
        },
        type_sort: {
          val: 0,
          oldVal: 0,
          init: 0,
          msg: "",
          state: 0,
        },
        type_key: {
          val: "",
          oldVal: "",
          init: "",
          msg: "",
          state: 0,
          reCheckField: 'type_name',
        },
        seo_key: {
          val: "",
          oldVal: "",
          init: "",
          msg: "",
          state: 0,
        }
      },
      api: '',
      queryParams : {},
      showLogoDialog: false,
      fileType: db_base.fileType.svg,
      loading: false,
    }
  },
  computed: {
    tags () {
      // 拆分tags
      let tags = this.formType.seo_key.val
      if (!tags) {
        return [];
      }
      // 去除空字符串
      tags = tags.replace(/\s/g,'')
      let tagArr = tags.split(',')
      // 标签去重
      tagArr = [...new Set(tagArr)]
      // 移除空标签
      tagArr = tagArr.filter(item => item)
      return tagArr
    }
  },
  mounted() {

    // fieldCheck.checkField('type',this.form.type.val)
    // formVerify.checkForm(this.form, true);
    console.log(formVerify);

  },
  methods: {
    /**
     * 初始化编辑器
     * @param id
     * @param title
     * @param api
     * @param object
     */
    init (title, api, object, queryParams) {

      this.api = api
      console.log('init')
      console.log(queryParams)
      this.queryParams = queryParams ? queryParams : {}
      if (!api){
        this.$message.error('请设置api地址')
        throw new Error('请设置api地址')
      }
      let type = {
        ...emptyType,
        ...object
      }
      if(object) {
        this.typeId = object.type_id
        this.title = `编辑${title}`
      }else{
        this.typeId = ''
        this.title = `新增${title}`
      }
      this.formType.type_name.init = type.type_name
      this.formType.type_logo.init = type.type_logo
      this.formType.type_sort.init = type.type_sort
      this.formType.type_key.init = type.type_key
      this.formType.seo_key.init = type.seo_key
      this.isInitialized = true
      formVerify = new FormVerify(
        this.formType,
        fieldCheck,
      )
      formVerify.init()
      formVerify.onLog = (msg) => {
        console.log(msg);
      };
    },
    updateQueryParams(params){
      this.queryParams = params
    },
    initForm() {

    },
    close () {
      this.isInitialized = false
      this.$emit('close')
    },
    handleSave () {
      this.executeSubmitData()
    },
    deleteTag(tag){
      let tagArr = this.tags
      let index = tagArr.indexOf(tag)
      tagArr.splice(index, 1)
      this.formType.seo_key.val = tagArr.join(',')
      this.formType.seo_key.msg = ''
    },
    handleCancel () {
      this.close()
    },
    handleReset() {
      this.initForm()
    },
    openLogoHandle() {
      this.showLogoDialog = true
    },
    closeLogoHandle() {
      this.showLogoDialog = false
    },
    selectImageHandle(fileData){
      console.log('okHandle');
      console.log(fileData);
      this.showLogoDialog = false;
      // 选择封面图片
      this.formType.type_logo.val = fileData.filePath;
      this.formType.type_logo.init = fileData.filePath;
      this.formType.type_logo.msg = '';
      this.formType.type_logo.state = 0;
      this.formType.type_logo.showText = fileData.filePath;
    },
    async executeSubmitData(){
      if(!this.isInitialized)
      {
        throw new Error('请先初始化类别编辑器')
      }
      let url = this.api;
      // 拼接param参数
      if(this.typeId){
         this.queryParams.id = this.typeId
      }
      url = urlAddParam(url, this.queryParams)
      console.log(url)
      // 检测参数
      if(!formVerify.check()) {
          return this.$message.error('参数错误')
      }
      let params = formVerify.getFormData()
      console.log(this.queryParams)
      params = {
        ...params,
        ...this.queryParams,
      }
      console.log(params)
      let [err, res] = await handle(axios.post(url, params))
      if(err){
        this.$message.error(`[${this.title}] 失败:${err.message}`)
        console.log(err)
        return err
      }
      let result = res.data
      if(result.code !== rCode.OK) {
        this.$message.error(`[${this.title}] 失败:${result.msg}`)
        return result
      }
      this.$message.success(`[${this.title}] 成功`)
      this.close()
    }


  }
}
</script>

<template>
  <div class="w-full ">
    <rounded-title class="text-xl">
      <span>{{ title }}</span>
    </rounded-title>

    <input-row class="mt-2" :msg="formType.type_name.msg"
               label="类型名称">
      <a-input v-model="formType.type_name.val" placeholder="类型名称"></a-input>
    </input-row>
    <input-row class="mt-2" :msg="formType.type_logo.msg"
               label="类型logo">
      <div class="svg-upload">
        <svg-icon  :svgHref="formType.type_logo.val"></svg-icon>
        <div v-if="!formType.type_logo.val" class="null-box">
          选择图标
        </div>
        <div class="absolute w-full h-full left-0 top-0
              justify-center text-white bg-gray-400
              items-center text-2xl flex opacity-0 hover:opacity-70"
             @click="openLogoHandle"
        >
          点击选择图标文件
        </div>
      </div>
    </input-row>
    <input-row class="mt-2" :msg="formType.type_sort.msg"
               label="排序">
      <a-input-number v-model="formType.type_sort.val"
                      placeholder="排序"></a-input-number>
    </input-row>
    <input-row class="mt-2" :msg="formType.type_key.msg"
               label="类型关键字key">
      <a-tooltip>
        <template slot="title">
          用于浏览器的搜索关键字, 优化用户访问体验, 禁止重复, 为英文字母
        </template>
        <a-input v-model="formType.type_key.val" placeholder="类型关键字key"></a-input>
      </a-tooltip>
    </input-row>


    <input-row class="mt-2" :msg="formType.seo_key.msg"
               label="seo关键字">
      <a-tooltip>
        <template slot="title">
          搜索引擎关注的关键字，多个用英文逗号隔开
        </template>
        <a-input v-model="formType.seo_key.val" placeholder="seo关键字"></a-input>
      </a-tooltip>

    </input-row>

    <input-row class="mt-2"
               label="">
      <div class="tags">
        <a-tag
          v-for="tag in tags"
          :key="tag"
          color="#2db7f5"
          closable @close="deleteTag"
        >
          {{ tag }}
        </a-tag>
      </div>
    </input-row>

    <div class="mt-2">
      <a-button type="primary" @click="handleReset">重置</a-button>
      <a-button type="primary" @click="handleSave">确认</a-button>
    </div>

    <pop :show="showLogoDialog" :loading="loading">
      <pop-card>
        <template slot="close-group">
          <a-button type="danger" @click="closeLogoHandle">关闭</a-button>
        </template>
        <image-table
          class="w-full h-full"
          :fileType="fileType"
          @cancel="closeLogoHandle"
          @ok="selectImageHandle">
        </image-table>
      </pop-card>
    </pop>
  </div>
</template>

<style scoped>
.svg-upload{
  width: 90px;
  height: 90px;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  border: 1px solid #ccc;
  border-radius: 5px;
  font-size: 45px;
}
.svg-upload .null-box{
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 20px;
}
.tags{
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-items: center;
}
</style>
