<template v-if="isShow">
  <!-- 列表选择弹窗 -->
  <f-dialog
    ref="dialog"
    title="遥控器设计器配置"
    :initData="handleInitData" 
    :isDetermine="dialogType!=='detail'"
    :beforeClose="handleBeforeClose"
    width="1550px"
  >
    <template #contain>
      <h3>遥控器基础配置</h3>
      <f-form
        ref="ruleForm"
        :form="fromData"
        :disabled="dialogType==='detail'"
        :config="fromDataConfig"
        :rules="fromRules"
        label-position="left"
        :key="fromKey"
        :inline="true"
        :column="6"
      />
      <h3>遥控器布局配置</h3>
      <div class="box">
        <div class="box-btns">
          <h3>组件库</h3>
          <div class="box-btns-cpns">
            <div v-for="(item, index) in cpnsList" :key="index"  class="box-btns-cpns-cpn" @click="addCpns(item)">
              <span class="iconfont" :class="item.classType"></span>
              <p>{{ item.text }}</p>
            </div>
          </div>
        </div>
        <div class="box-canvs">
          <div class="box-canvs-main" :style="{ backgroundImage: `url(${fromData.backgroundPictureUrl?baseUrl+fromData.backgroundPictureUrl:''})` }">
            <grid-layout 
              :key="pageArray.length"
              :layout.sync="pageArray"
              :col-num="6"
              :row-height="30"
              :is-draggable="true"
              :is-resizable="false"
              :is-mirrored="false"
              :vertical-compact="false"
              :prevent-collision="true"
              :margin="[10, 10]"
              :use-css-transforms="false"
              :auto-size="false"
              class="box-canvs-main-screen"
            >
              <grid-item 
                v-for="(item, index) in pageArray"
                :key="index+'_'+item.h+'_'+item.w"
                :x="Number(item.x)"
                :y="Number(item.y)"
                :w="Number(item.w)"
                :h="Number(item.h)"
                :i="item.i"
                @dblclick.native="showSeting(index)"
              >
                <div class="box-canvs-main-span">
                  <div
                    style="width: 100%; height: 100%;display: flex;align-items: center;justify-content: center; background-size: contain; background-repeat: no-repeat;"
                    :style="{
                      borderColor:item.borderColor,
                      borderWidth:item.border,
                      borderStyle:'solid',
                      borderRadius:item.borderRadius,
                      fontSize:item.fontSize,
                      backgroundColor:item.background,
                      color:item.color,
                      backgroundImage:item.backgroundImage?`url(${baseUrl}${item.backgroundImage})`:'',
                    }"
                  >
                    {{item.content}}
                  </div>
                  <i class="el-icon-close" @click.stop="removeBtn(index)" />
                </div>
              </grid-item>
            </grid-layout>
          </div>
        </div>
        <div class="box-set">
          <el-tabs v-if="isShowSeting" v-model="activeName" type="card">
            <el-tab-pane label="组件基础配置" name="first" v-if="pageArray[currentCpn].type  == 'button'">
              <f-form
                ref="btnForm"
                :key="btnFromKey"
                :form="pageArray[currentCpn]"
                :config="btnDataConfig"
                :rules="btnRules"
                label-position="left"
                :column="1"
              />
            </el-tab-pane>
            <el-tab-pane label="组件样式配置" name="second">
              <f-form
                ref="btnClassForm"
                :key="btnFromKey"
                :form="pageArray[currentCpn]"
                :config="btnClassConfig"
                label-position="left"
                :column="1"
              />
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </template>
  </f-dialog>
</template>
<script>
import { addTemplateApi } from '@/api/template/addTemplate'
import { formConfig, btnFormConfig } from './config'
import { cpnsList } from '../../../../mock/cpnsList'
export default {
  name: "DetailDialog",
  props: {
    // 表单数据
    rowData:{
      type:Object,
      default: () => ({})
    },
    // 表单类型 add detail edit
    dialogType:{
      type:String,
      default:'add'
    },
    allBase: {
      type: Array,
      default: () => []
    },
    allButton: {
      type: Array,
      default: () => []
    },
    useStatus: {
      type: Array,
      default: () => []
    }
  },

  data() {
    return {
      // tab
      activeName: 'second',
      cpnsList,
      // 数据对象
      fromData:{},
      fromDataConfig: [],
      // 表单验证
      fromRules: {
        name: [{required: true, message: '请输入模版名称'}],
        status: [{required: true, message: '请选择状态'}],
        baseId: [{required: true, message: '请选择基础库'}],
      },
      // 表单key
      fromKey:0,
      pageArray: [],

      // 按钮配置相关
      btnFromShow: false,
      btnData: {},
      btnDataConfig: btnFormConfig(),
      btnFromKey: 0,
      btnRules: {
        typeNum:[{required: true, message: '请选择按钮类型'}],
        defValue:[{required: true, message: '请输入默认值'}],
        bandValue:[{required: true, message: '请输入波段值，默认38000'}],
        bootCode:[{required: true, message: '请输入引导码'}],
        bootCodeSend:[{required: true, message: '请输入引导码发送次数'}],
        dateCode:[{required: true, message: '请输入数据码'}],
      },
      currentCpn: '', //已选择的组件下标
      isShowSeting:false,
      baseUrl:process.env.VUE_APP_FILE_STATIC,
    };
  },
  computed: {
    pageArrayCount() {
      return this.pageArray.length;
    },
    btnClassConfig() {
      let config = [
        {
          itemType: 'input',
          prop: 'w',
          label: '宽度',
          attrs: {
            placeholder: '请输入宽度',
          }
        },
        {
          itemType: 'input',
          prop: 'h',
          label: '高度',
          attrs: {
            placeholder: '请输入高度',
          }
        }
      ]
      const { currentCpn, pageArray } = this
      if (!pageArray[currentCpn]) return []
      const { type } = pageArray[currentCpn]
      if (type === 'button') {
        config = [
          ...config,
          {
            itemType: 'input',
            prop: 'content',
            label: '按钮文字'
          },
          {
            itemType: 'input',
            prop: 'border',
            label: '边框粗细'
          },
          {
            itemType: 'color',
            prop: 'borderColor',
            label: '边框颜色'
          },
          {
            itemType: 'input',
            prop: 'borderRadius',
            label: '圆角尺寸'
          },
          {
            itemType: 'input',
            prop: 'fontSize',
            label: '字体大小'
          },
          {
            itemType: 'color',
            prop: 'background',
            label: '背景颜色'
          },
          {
            itemType: 'color',
            prop: 'color',
            label: '字体颜色'
          }
        ]
      }
      if (type === 'text') {
        config = [
          ...config,
          {
            itemType: 'input',
            prop: 'content',
            label: '文字'
          },
          {
            itemType: 'input',
            prop: 'fontSize',
            label: '字体大小'
          },
          {
            itemType: 'color',
            prop: 'color',
            label: '字体颜色'
          }
        ]
      }
      if(type === 'image') {
        config = [
          ...config,
          {
            itemType: 'fileUpload',
            prop: 'backgroundImage',
            label: '图片'
          }
        ]
      }
      return config
    }
  },
  methods: {
    // 显示弹窗
    show() {
      this.fromDataConfig = formConfig.call(this)
      this.$refs.dialog.show();
    },
    // 初始化表单数据
    initFormData(fromData) {
      this.fromData = {
        content:'',
        ...fromData
      }
      this.fromKey++;
    },
    // 初始化按钮表单数据
    initBtnFormData(index) {
      this.isShowSeting = false
      this.currentCpn = index
      this.$nextTick(() => {
        this.isShowSeting = true
        this.btnFromKey++
      })
    },
    // 详情
    async handleInitData() {
      const {dialogType,rowData} = this
      if (dialogType === 'add') {
        this.pageArray = []
        this.initFormData({ })
        return
      }
      // 调接口获取详情
      const res = await addTemplateApi.configDetail({ id: rowData.id });
      if (res.code !== 200) return this.initFormData({ })
      const from = { ...res.data, baseId: res.data.baseId.toString() }
      this.pageArray = JSON.parse(res.data.components).map((item, index) => ({
        ...item,
        x: Number(item.x),
        y: Number(item.y),
        w: Number(item.w),
        h: Number(item.h),
        i: index,
        text: item.content
      }))
      this.initFormData(from);
    },
    // 关闭之前回调.
    async handleBeforeClose(type) {
      if (type !='ok') {
        return true
      };
      // 按钮配置项校验
      let validateResult = null
      for(let index = 0; index <= this.pageArray.length-1; index++) {
        validateResult = this.validateBtn(this.pageArray[index])
        if (validateResult !== true) {
          this.isShowSeting = true
          this.currentCpn = index
          this.activeName = 'first'
          this.$message({
            message: validateResult,
            type: 'warning'
          });
          return false
        }
      }
      // 布局配置项
      const validate = await this.$refs.ruleForm.validate();
      if (!validate) return false;

      const params = {
        ...this.fromData,
        components: JSON.stringify(this.pageArray),
        baseId: Number(this.fromData.baseId)
      }
      //  调接口更新数据
      const res = await addTemplateApi.configAddOrEdit(params);
      if (res.code !== 200) {
        this.$modal.msgError(res.msg)
        return false
      }

      this.$emit('updateList')
      this.initFormData({})
      return true
    },
    // 添加
    addCpns(item) {
      // this.
      this.pageArray.push({ w: 2, h: 2, x: 1, y: this.pageArray.map(item => item?.y).sort()[this.pageArray.length-1] || 1, i: this.pageArrayCount, ...item })
      this.initBtnFormData(this.pageArray.length-1);
    },
    removeBtn(index) {
      const tmpList = this.pageArray.concat();
      tmpList.splice(index, 1)
      this.isShowSeting = false
      this.currentCpn = '';
      this.pageArray = tmpList

    },
    showSeting(index) {
      this.activeName = 'second'
      this.initBtnFormData(index)
    },
    // 校验按钮属性
    validateBtn(obj) {
      if (obj.type != 'button') return true
      for(const item of Object.keys(this.btnRules)) {
        if (!obj[item]) return this.btnRules[item][0].message
        if (obj.typeNum == '0' && !obj?.addSubMax) return '加减型需输入最大值'
        if (obj.typeNum == '0' && !obj?.addSubMin) return '加减型需输入最小值'
        if (obj.typeNum == '0' && obj?.addSubMax <= obj?.addSubMin) return '加减型最大值要大于最小值'
      }
      return true
    }
  },


}
</script>
<style scoped lang="scss">
h3 {
  font-weight: 700;
  padding-bottom: 8px;
  border-bottom: 2px solid #ccc;
}
.box {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  &-btns, &-canvs {
    width: 375px;
    height: 770px;
    border: 1px solid #000;
  }
  &-btns {
    display: flex;
    flex-direction: column;
    >h4, >h3 {
      text-align: center;
    }
    &-cpns {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      .box-btns-cpns-cpn {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: space-evenly;
        width: 80px;
        height: 80px;
        background: #f5f5f5;
        margin-bottom: 15px;
        span {
          font-size: 28px;
        }
        p {
          margin: 0;
          padding: 0;
        }
      }
    }
    &-items {
      overflow-y: scroll;
      &::-webkit-scrollbar {
        display: none;
      }  
    }
    &-item {
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 20px;
      background-color:#0a0a23;
      color: #fff;
      border:none;
      border-radius: 10px;
      box-shadow: 0px 0px 2px 2px rgb(0,0,0);

      span {
        position: relative;
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 100%;
        i {
          position: absolute;
          top: 50%;
          right: 0;
          transform: translateY(-50%);
          font-size: 16px;
        }
      }
    }
  }
  &-canvs {
    position: relative;
    background: url(../../../../assets/images/mobile-bg.jpg) no-repeat;
    background-size: 100%;
    border: none;
    margin: 0 20px;
    &-main {
      position: absolute;
      top: 90px;
      left: 20px;
      width: 333px;
      height: 585px;
      border: 1px solid #000;
      border-radius: 4px;
      overflow-y: scroll;
      background-color: #fff;
      background-size: cover;
      &::-webkit-scrollbar {
        display: none;
      }
      .box-canvs-main-span {
        position: relative;
        background: #ffc0cb29;
        border: 1px dashed #00000033;
        height: 100%;
        width: 100%;
        i{
          position: absolute;
          right: 0px;
          top: 0px;
        }
      }
    }
  }
  &-set {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    min-height: 667px;
    overflow-y: scroll;
    &::-webkit-scrollbar {
      display: none;
    }
    h3 {
      font-weight: bold;
    }
  }
}
</style>