<template>
  <div class="xd-footer-setting">
    <draggable
      :list="form"
      :disabled="form.length === 0"
      class="xd-upload__list-box"
      @start="dragging = true"
      @end="dragging = false"
      @update="handleUpdate"
    >
      <div class="xd-footer-setting__item" v-for="(item,index) in form" :key="item.key">
        <div>
          <div class="xd-footer-setting__item-path subTitle" v-if="showField.path">
            <div>路径：</div>
            <div>
              <xd-select-pages-path
                size="mini"
                clearable
                :disabled="disabled"
                v-model="item.path"
                :default-value="item.path"
                :setting="setting"
                @onChange="(select)=>{handleSelectPath(select, index)}"
              ></xd-select-pages-path>
            </div>
          </div>
          <div v-if="showField.params" class="params">内部页面设置自定义参数，参数格式:<span data-v-9ef1d2da="" style="color: red;">id=4085&amp;type=1</span></div>
          <div class="xd-footer-setting__item-name subTitle" v-if="showField.params">
            <div>参数：</div>
            <div>
              <el-input
                clearable
                :disabled="disabled"
                size="small"
                @input="handleInput"
                v-model="item.params"
                placeholder="请输入自定义参数"></el-input>
            </div>
          </div>
          <div class="xd-footer-setting__item-name subTitle" v-if="showField.path">
            <div>标题：</div>
            <div>
              <el-input
                clearable
                :disabled="disabled"
                size="small"
                @input="handleInput"
                v-model="item.name"
                placeholder="请输入标题"></el-input>
            </div>
          </div>
          <div class="xd-footer-setting__item-name subTitle" v-if="showField.subTitle">
            <div>副标题：</div>
            <div>
              <el-input
                clearable
                :disabled="disabled"
                size="small"
                @input="handleInput"
                v-model="item.subName"
                placeholder="请输入副标题"></el-input>
            </div>
          </div>
          <div class="xd-footer-setting__item-num subTitle" v-if="showField.notice">
            <div>消息：</div>
            <div>
              <xd-select-list
                style="width: 100%"
                filterable
                clearable
                :disabled="disabled"
                size="small"
                :default-value="item.api"
                :list="noticeList"
                v-model="item.api"
                placeholder="请选择消息类型接口"
                @change="()=>{update();change()}"
              ></xd-select-list>
            </div>
          </div>
          <!--icon-->
          <template v-if="showField.icon">
          <div class="xd-footer-setting__item-icon subTitle" v-if="iconInput" >
            <div>图标：</div>
            <div>
              <el-input
                clearable
                :disabled="disabled"
                size="small"
                v-model="item.icon"
                placeholder="请输入页面ICON"
                @input="handleInput"
              ></el-input>
            </div>
          </div>
          <div class="xd-footer-setting__item-icon subTitle" v-else >
            <div>图标：</div>
            <div>
              <xd-select-list
                style="width: 100%"
                filterable
                clearable
                :disabled="disabled"
                size="small"
                :default-value="item.icon"
                :list="iconList"
                v-model="item.icon"
                placeholder="请选择消息类型接口"
                @change="()=>{update();change()}"
              ></xd-select-list>
            </div>
          </div>
          </template>
          <!--icon-->
          <!--image-->
          <template v-if="showField.image || showField.actImage">
            <div class="xd-footer-setting__item-name subTitle" v-if="showField.image">
              <div>{{imageTitle}}：</div>
              <div>
                <xd-upload
                  v-model="item['image']"
                  :default-value="item['image']"
                  :action="'action'"
                  :size=".5"
                  :type="['jpg','jpeg','png','gif']"
                  style-type="one"
                  upload-type="aliyun"
                  :item='{slot: true}'
                  :showtype="true"
                  @success="(...args)=>{handleInput();handleSuccess(args)}"
                  @onApiSuccessUrl="handleApiSuccessUrl"
                  @onGetParamsAndHeader="handleGetParamsAndHeader"
                  @on-delete="handleInput();"
                >
                  <template slot-scope="scope">
                    <div class="xd-footer-setting__upload" :class="{has:scope.image.url}">
                      <xd-font-icon
                        class="xd-footer-setting__upload-icon"
                        icon="iconjia"
                        size="18"
                        :color="!scope.image.url?'#999': 'rgba(0,0,0,0)'"
                      ></xd-font-icon>
                      <img v-if="scope.image.path" :src="scope.image.path" alt="icon"></img>
                    </div>
                  </template>
                  <div class="tips" slot="tip">图片格式:<span>JPG/JPEG/PNG/GIF</span>，尺寸:<span>128*128</span>像素，且不超过<span>500</span>kb</div>
                </xd-upload>
              </div>
            </div>
            <div class="xd-footer-setting__item-name subTitle" v-if="showField.actImage">
              <div>划过图标：</div>
              <div>
                <xd-upload
                  v-model="item['actImage']"
                  :default-value="item['actImage']"
                  :action="'action'"
                  :size=".5"
                  :type="['jpg','jpeg','png','gif']"
                  style-type="one"
                  upload-type="aliyun"
                  :item='{slot: true}'
                  :showtype="true"
                  @success="(...args)=>{handleInput();handleSuccess(args)}"
                  @onApiSuccessUrl="handleApiSuccessUrl"
                  @onGetParamsAndHeader="handleGetParamsAndHeader"
                  @on-delete="handleInput();"
                >
                  <template slot-scope="scope">
                    <div class="xd-footer-setting__upload" :class="{has:scope.image.url}">
                      <xd-font-icon
                        class="xd-footer-setting__upload-icon"
                        icon="iconjia"
                        size="18"
                        :color="!scope.image.url?'#999': 'rgba(0,0,0,0)'"
                      ></xd-font-icon>
                      <img v-if="scope.image.path" :src="scope.image.path" alt="icon"></img>
                    </div>
                  </template>
                  <div class="tips" slot="tip">图片格式:<span>JPG/JPEG/PNG/GIF</span>，尺寸:<span>128*128</span>像素，且不超过<span>500</span>kb</div>
                </xd-upload>
              </div>
            </div>
          </template>
          <!--image-->
          <div class="xd-footer-setting__item-size subTitle" v-if="showField.icon">
            <div>大小：</div>
            <div>
              <el-input
                clearable
                :disabled="disabled"
                size="small"
                v-model="item.size"
                placeholder="请输入页面ICON大小"
                @input="handleInput"
              ></el-input>
            </div>
          </div>
        </div>
        <div v-if="hideAdd=== false">
          <i class="el-icon-circle-plus" v-if="(index + 1) === form.length && !disabled" @click="add"></i>
          <i class="el-icon-remove" v-if="form.length > 1 && !disabled" @click="cut(index)"></i>
        </div>
      </div>
    </draggable>
  </div>
</template>

<script>
import draggable from 'vuedraggable';
import emitter from 'element-ui/src/mixins/emitter';
import XdSelectPagesPath from "@/components/formItem/XdSelectPagesPath";
import XdSelectList from "@/components/XdSelectList";
import XdUpload from "@/components/XdUpload.vue";
import XdFontIcon from "@/components/XdFontIcon.vue";

export default {
  name: "XdFooterSetting",
  components:{
    XdSelectList,
    XdSelectPagesPath,
    draggable,
    XdUpload,
    XdFontIcon
  },
  mixins: [emitter],
  props:{
    defaultValue: {
      type: Array | null,
      default() {
        return null
      },
    },

    maps: {
      type: Object | null,
      default() {
        return null
      },
    },

    setting: {
      type: Object,
      default() {
        return {

        }
      },
    },

    disabled: {
      type: Boolean,
      default: true,
    },

    size: {
      type: String,
      default: 'medium', //medium / small / mini
    },

    placeholder: {
      type: Object,
      default() {
        return {

        }
      },
    },

    required: {
      type: Boolean,
      default: false,
    },

    //是否启用自定义校验器
    useCustomRules: {
      type: Boolean,
      default: false,
    },

    //数字字符串 转 数字
    isNumber: {
      type: Boolean,
      default: true,
    },

    //自定义方法
    handleCustom: {
      type: Function || null,
      default: null
    },

  },
  computed:{
    imageTitle(){
      if(this.showField.actImage) return '当前图片';
      return '图片'
    }
  },
  data(){
    return {
      max: 5, //最大支持5个菜单
      emptyData: {path: null, params: '', image:'', actImage:'', icon: '', name: '', size: 18, api: '', subName: ''},
      form: [],
      timer: null,
      iconInput:true,
      iconList:[],

      //noticeList
      noticeList: [],
      hideAdd: false,

      //是否显示字段
      showField: {
        path: true,
        notice: true,
        subTitle: false,
        icon: false,
        params: false,
        image: false,
        actImage:false
      },

      dragging: false
    }
  },

  created(){
    //设置默认值
    if(typeof this.handleCustom !== 'function') {
      throw new Error(`请实现handleCustom自定义方法`);
    }
    this.handleCustom({
      action: 'number',
      data: {
        cb: (res) => {
          this.noticeList = res;
          console.log('handleCustom.number', this.noticeList);
          this.init();
        }
      }
    });
  },

  methods: {
    handleUpdate(args){
      this.$nextTick(()=>{
        this.update();
        this.change();
      })
    },
    init(){
      if (this.defaultValue !== null
        && this.$xdHelper.checkVarType(this.defaultValue) === 'array'
        && this.defaultValue.length > 0
      ) {
        this.form = this.defaultValue.map(item => {
          return {
            ...item,
            image: item['image'] || '',
            actImage: item['actImage'] || '',
            key: this.$xdHelper.randomChar(20),
            size: item.size || 18,
            name: item.name ? item.name : item.path?.label
          }
        });
      } else {
        this.form.push(this.$xdHelper.cloneDeep({...this.emptyData, key: this.$xdHelper.randomChar(20)}));
      }

      //显示字段
      if(this.setting.showField &&
        this.$xdHelper.checkVarType(this.setting.showField) === 'object'
      ) {
        this.showField = Object.assign({},this.showField,this.setting.showField);
      }


      //传入icons列表使用选择模式（平滑升级）
      if(this.setting['icons'] && this.setting['icons'].length > 0) {
        this.iconInput = false;
        this.iconList = this.setting['icons'];
      }

      //是否隐藏添加与删除按钮
      if(this.setting && typeof this.setting['hideAdd'] === 'boolean') {
        this.hideAdd = this.setting['hideAdd'];
      }

      this.update()
    },

    handleSelectPath(select,index){
      let item = this.$xdHelper.cloneDeep(this.form[index]);
      item.path = select;
      item['key'] = this.$xdHelper.randomChar(20);
      if(!item.name){
        item.name = select.label;
        this.form.splice(index, 1, item);
        console.log('handleSelectPath', select, item)
      }
      this.update();
      this.change();
    },

    handleInput(){
      if(this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        this.update();
        this.change()
      }, 500)
    },

    add(){
      if(this.form.length >= this.max){
        this.$message.error(`最多添加${this.max}个`);
        return
      }
      let temp = this.$xdHelper.cloneDeep(this.emptyData);
      temp = {...temp, key: this.$xdHelper.randomChar(20)};
      this.form.push(temp);
      this.update();
      this.change()
    },

    cut(index) {
      this.form.splice(index, 1);
      this.update();
      this.change()
    },

    /**
     * @description 需要校验检查参数是正确处理方法
     */
    checkParams(){
      //验证
      if(this.required) {
        let list = [];

        //需要验证路径和图标
        if(this.showField.path && this.showField.icon) {
          list = this.form.filter(item => {
            return this.$xdHelper.checkVarType(item.path) === 'object' && item.name && item.icon;
          })
        }

        //需要验证路径和图标不验证
        if(this.showField.path && !this.showField.icon) {
          list = this.form.filter(item => {
            return this.$xdHelper.checkVarType(item.path) === 'object' && item.name;
          })
        }

        list = list.map(item=>{
          if (item['key']) delete item['key'];
          if (item.path) {
            const path = item.path.value.split('?')[0];
            item.path.value = `${path}${item.params ? `?${item.params}` : ''}`;
          }
          return item;
        });


        if(list.length === this.form.length) return list;
        else return []
      }

      //非验证
      else return this.form.map(item=>{
        if(item['key']) delete item['key'];
        if (item.path) {
          const path = item.path.value.split('?')[0];
          item.path.value = `${path}${item.params ? `?${item.params}` : ''}`;
        }
        console.log(item,'apapapap');
        return item;
      });
    },

    /**
     * @description 数据改变事件
     */
    change(){
      this.$emit('onChange', this.checkParams())
    },


    /**
     * @description 双向绑定数据处理
     */
    update(){
      this.$emit('input', this.checkParams());
      if (this.$parent.$options['componentName'] === 'ElFormItem') {
        this.dispatch('ElFormItem', 'el.form.change', [this.checkParams()]);
      }
    },


  }
}
</script>

<style scoped lang="scss">
.xd-footer-setting {

  &__item {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    box-shadow: 0 0 10px rgba(0,0,0,.2);
    margin: 0 0 10px 0;
    padding: 10px;
    border-radius: 6px;
    overflow: hidden;
    box-sizing:border-box;
    width: 100%;

    &:hover {
      cursor: move;
    }

    & > div:first-child {
      flex: 1;
    }

    & > div:nth-child(2) {
      width: 50px;
      margin-left: 10px;
      border-left: 1px solid #efefef;
      min-height: 100px;
      font-size: 20px;
      box-sizing: border-box;
      padding: 0 0 0 10px;
      display: flex;
      justify-content: center;
      align-items: center;


      & > i {
        cursor: pointer;
        &.el-icon-remove {
          color: $red;
        }

        &.el-icon-circle-plus {
          color: $blue;
        }
      }
    }

    &-path,&-name,&-icon, &-num, &-size{
      display: flex;
      justify-content: flex-start;
      align-items: center;
      margin: 0 0 10px;
      width: 100%;

      ::v-deep .xd-upload {
        height: 50px;
        display: flex;
        justify-content: flex-start;
        align-items: center;
      }

      ::v-deep .xd-upload__one {
        height: 50px!important;
        margin-right: 10px;
      }

      ::v-deep .xd-upload__tip {
        margin-top: 0!important;
        padding-top: 0!important;
      }

      ::v-deep .xd-upload__one-btn-del {
        width: 20px;
        height: 20px;
      }

      ::v-deep .xd-select-pages-path {
        min-width: 255px!important;
      }

      &> div {
        flex-shrink: 0;

        &:first-child {
          text-align: left;
        }
      }
    }

    &-size {
      margin-bottom: 0;
    }

    & div.subTitle {
      flex-shrink: 0;
      & > div:first-child {
        width: 70px;
        flex-shrink: 0;
      }
      &  > div:last-child {
        flex: 1;
      }
    }

  }
  &__upload {
    border: #999 dashed 2px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    border-radius: 6px;
    width: 50px;
    height: 50px;

    &-input {
      margin-bottom: 10px;
    }

    &-icon {
      position: absolute;
      left: 0;
      right: 0;
      height: 100%;
      width: 100%;
    }

    & > img {
      max-width: 100%;
      max-height: 100%;
    }

    &:hover, &:hover.has {
      border: #42B983 dashed 2px;
    }

    &:hover.has &-icon {
      color: rgba(255, 255, 255, .7) !important;
      background: rgba(0, 0, 0, .05);
    }
  }
}

@media screen and (max-width: 768px) {
  .xd-footer-setting {
  }
}

::v-deep .upload_one_m {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  &> *:nth-child(1) {
    flex-shrink: 0;
  }

  & > *:nth-child(2) {
    margin-left: 10px;
  }
}

.params {
  font-size: 12px;
  color: rgb(153, 153, 153);
  line-height: 15px;
  padding-bottom: 5px;
}
.tips {
  font-size: 12px;
  color: #333;
  line-height: 15px;

  & > span {
    color: red;
  }
}
</style>
