<template>
  <el-card class="app-container">
    <div class="app-container__title">广告位添加</div>
    <div class="app-container__body">
      <xd-base-field
        ref="poster"
        v-if="status && listForm.length > 0"
        v-model="listValue"
        :list="listForm"
        label-width="100px"
        @success="handleSuccess"
        @onApiSuccessUrl="handleApiSuccessUrl"
        @onGetParamsAndHeader="handleGetParamsAndHeader"
      >
        <template slot="custom" slot-scope="scope">
          <el-form
            :label-width="scope.width"
            :model="customForm"
            :rules="customRules"
            ref="customForm"
          >
            <el-form-item
              v-if="scope.form['jump_type'] === 1"
              label="跳转地址"
              prop="redirect_url"
            >
              <el-input
                v-model="customForm['redirect_url']"
                placeholder="请输入跳转地址"
                class="input40"
              ></el-input>
            </el-form-item>
            <el-form-item
              v-if="scope.form['jump_type'] === 2"
              label="跳转条件"
              prop="package_type"
            >
              <xd-select-list
                class="input20"
                placeholder="请输入跳转到指定套餐分类"
                :list="null"
                v-model="customForm['package_type']"
                :default-value="[]"
              ></xd-select-list>
            </el-form-item>
            <el-form-item
              label="编辑器"
              prop="tinymceContent"
            >
              <xd-tinymce
                v-model="customForm.tinymceContent"
                :height="200"
                :image-config="imageConfig"
                @success="handleSuccess"
                @onApiSuccessUrl="handleApiSuccessUrl"
                @onGetParamsAndHeader="handleGetParamsAndHeader"
                @change="handleTinymceChange"
              ></xd-tinymce>
            </el-form-item>
            <el-form-item
              label="编辑器"
              prop="wangEditorContent"
            >
              <xd-wang-editor
                action="https://sandbox-c.jufubao.cn/api/admin/common/upload"
                :height="200"
                :z-index="10000"
                v-model="customForm.wangEditorContent"
                @blur="handleWangEditorChange"
              ></xd-wang-editor>
            </el-form-item>

          </el-form>
        </template>
      </xd-base-field>
      <div class="adjust-btn">
        <el-button @click="handleClick('adjustCard')" type="primary">提交</el-button>
      </div>
    </div>
  </el-card>
</template>

<script>
  import XdBaseField from "@/components/XdBaseField";
  import XdSelectList from "@/components/XdSelectList";
  import {genUpToken} from "./../../views/scripts/qiniu"
  import XdTinymce from "@/components/XdTinymce";
  import XdWangEditor from "@/components/XdWangEditor";



  export default {
    name: "create",
    components: {
      XdBaseField,
      XdSelectList,
      XdTinymce,
      XdWangEditor
    },
    data(){
      return {
        listForm: [],
        listValue: {},

        imageConfig: { //null => 不启用图片上传功能
          sort: true,
          maxlen: 100,
          action: 'https://up-z1.qiniup.com',
          qiniuCdn: 'http://static.e56buy.com',
          size: 5,
          tipsformet: '上传文件格式：@imageType@，不超过@size@MB.',
          uploadType: 'qiniu', //aliyun , qiniu
          type: ['jpg', 'png', 'jpeg']
        },

        //自定义模块
        customForm:{
          redirect_url: '', //跳转地址
          package_type: '', //跳转到分类
          tinymceContent: '', //内容编辑器
          wangEditorContent: '', //内容编辑器
        },
        customRules: {
          redirect_url: {
            required: true,
            message: '请输入跳转地址',
            trigger: ['blur']
          },
          package_type: {
            required: true,
            message: '请输入跳转到指定套餐分类',
            trigger: ['blur', 'change']
          },
          tinymceContent:{
            required: true,
            message: '请输入内容',
            trigger: ['change']
          },
          wangEditorContent: {
            required: true,
            message: '请输入内容',
            trigger: ['blur']
          }
        },

        status: false, //初始化完成
      }
    },

    created(){
      this.initForm()
    },

    methods: {
      handleTinymceChange(){
        this.$refs.customForm.validateField('tinymceContent')
      },


      handleWangEditorChange() {
        this.$refs.customForm.validateField('wangEditorContent')
      },


      /**启动上传图片*******=======================================*/
      /**
       * @description 上传到本地服务器成功返回值时刻触发，设置url字段
       */
      handleApiSuccessUrl(result, resolve) {
        resolve(result.data['ObjectURL'])
      },
      /**
       * @description 上传参数设置
       * @param file
       * @param resolve
       */
      handleGetParamsAndHeader(file, resolve) {
        resolve({
          params: {
            token: genUpToken({
              accoutKey: 'bP3Ca5dtSJBNaWwMkihfhuE30CbAZnYrNzQm6eMN',
              serviceKey: 'pPNgWwRL3_Jlj7cPtpYbkhXn01EOZTtUhOs3NqZM',
              webSiteName: 'e56buystatic',
              staticUrl: 'http://static.e56buy.com',
            }),
            key: 'Xd' + this.$xdHelper.randomChar(30)
          }
        });
      },

      handleSuccess(res) {
        console.log(res)
      },
      /**启动上传图片*******=======================================*/

      /**
       * @description 初始化表单
       * @param params
       */
      initForm(...params) {
        let form = [
          {
            label: '广告位名称:', //label
            ele: 'el-input', //package 名称
            //text，textarea 和其他 原生 input 的 type 值
            //https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types
            type: 'text',
            valueKey: 'name', //form[valueKey]
            value: '', //v-model
            placeholder: '输入广告位名称',
            classNmae: 'input40', //样式名称 //input100,input80,input70,input60,input50,input40,input30,input20,
            rules: [
              {
                required: true,
                message: '请输入广告位名称',
                trigger: 'blur'
              },
            ]
          },
          {
            label: '广告位位置:', //label
            ele: 'xd-select-list', //package 名称
            valueKey: 'position', //form[valueKey]
            value: '', //v-model
            placeholder: '请选择广告位位置',
            multiple: false,
            list: [
              {"label": "万利达集团(750*300)", "value": 4},
              {"label": "中国联通(750*300)", "value": 5},
              {"label": "中国移动(750*300)", "value": 6},
              {"label": "味多美(750*300)", "value": 7},
            ],
            rules: {
              required: true,
              message: '请选择广告位位置',
              trigger: ['blur', 'change']
            },
          },
          {
            label: '跳转方式:', //label
            ele: 'xd-select-list', //package 名称
            valueKey: 'jump_type', //form[valueKey]
            value: 1, //v-model
            placeholder: '请选择跳转方式',
            multiple: false,
            list: [
              {"label": "链接", "value": 1},
              {"label": "条件", "value": 2},
            ],
            rules: {
              required: true,
              message: '请选择跳转方式',
              trigger: ['blur', 'change']
            },
          },
          {
            label: '', //label
            ele: 'slot', //package 名称
            slot: 'custom',
          },
          {
            label: '广告图片:', //label
            ele: 'xd-upload', //package 名称
            valueKey: 'img_url', //form[valueKey]
            value: {}, //v-model
            defaultValue: null, //默认图片对象
            slot: false, //按钮是否使用slot
            elinputClassName: 'input40',
            tipsformet: '上传文件格式：@imageType@，不超过@size@MB。',
            type: ['jpg', 'png', 'jpeg'],
            styleType: 'one', //其值：one=>单文件上传 auth=>证件正反面上传 list=>多文件上传
            uploadType: 'qiniu', //''=>API服务上传  qiniu=>七牛云OSS上传  aliyun=> 阿里云OSS上传
            size: 5, //5M
            action: 'https://up-z1.qiniup.com',
            qiniuCdn: 'http://static.e56buy.com', //七牛访问资源域名
            rules: [
              {required: true, message: '请上传图片', trigger: ['blur', 'change']},
            ]
          },
          {
            label: '排序:', //label
            ele: 'el-input', //package 名称
            //text，textarea 和其他 原生 input 的 type 值
            //https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types
            type: 'text',
            valueKey: 'sort', //form[valueKey]
            value: '', //v-model
            placeholder: '输入排序',
            classNmae: 'input20', //样式名称 //input100,input80,input70,input60,input50,input40,input30,input20,
          },
          {
            label: '状态:', //label
            ele: 'xd-select-status', //package 名称
            valueKey: 'status', //form[valueKey]
            value: 'Y', //v-model
            isall: false,
            backValueType: '', //返回值类型 1=>返回（Y,N）2=> [true|false] 3=>[1,0] 4=>[1,2]
            placeholder: '请选择',
            list: 'status', //status=>状态  best=>推荐  associate=>关联 yes=>是否 open=> 是否开启  check=>审核
          },
        ];

        this.listForm = form;
        this.status = true;
      },

      subumit(){
        return new Promise((resolve, reject) => {
          this.$refs['customForm'].validate((valid, error) => {
            if (valid) resolve(valid);
            else reject(valid, error);
          })
        });
      },


      /**
       * @description 提交数据事件
       */
      handleClick() {
        Promise.all([this.$refs['poster'].submit(), this.subumit()])
          .then(res => {
            console.log({...this.listValue, ...this.customForm})
          })
          .catch(res => {
            console.log('no')
          })
      }
    }
  }
</script>

<style scoped lang="scss">
  .app-container {

    &__title {
      font-size: 16px;
      line-height: 24px;
      padding: 0 0 20px;
      font-weight: bold;
    }

    &__body {
      & ::v-deep .el-tabs__content{
        padding-top: 20px;
      }
    }
  }

  .adjust-btn {
    margin-left: 100px;
  }
  @media screen and (max-width: 768px) {
    .app-container {
      &__title {
        padding: 0 0 10px;
      }

      & ::v-deep .el-card__body {
        padding: 10px;
      }

      &__body {
        & ::v-deep .el-tabs__content {
          padding-top: 10px;
        }
      }
    }
  }
</style>
