<template>
  <el-drawer ref="drawer" :destroy-on-close="true" :visible.sync="controlPropsVisible" :wrapper-closable="false"
             custom-class="es-modal"
             direction="rtl" size='55%' title="控件属性">
    <div class="es-drawer__content">
      <!--  通用属性    -->
      <ed-card v-if="showCommonProp" title="通用属性">
        <ed-form v-model="defaultForm" :form-desc="defaultFormDesc">
          <template v-slot:isLabelValueWrapper="scope">
            <el-form-item v-show="scope.desc.isShow" v-bind="scope.desc">
              <template #label>
                <span>存储为label</span>
                <el-tooltip class="item" effect="dark" placement="bottom">
                  <div slot="content">{{ labelTooltip }}</div>
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </template>
              <el-switch v-model="scope.model.isLabelValue"></el-switch>
            </el-form-item>
          </template>
        </ed-form>
      </ed-card>

      <!-- 独立属性 -->
      <ed-card :title="component.name">
        <el-form :model="controlProps" label-position="left" label-width="120px">
          <el-form-item v-for="(item, index) in component.attribute" v-if="isShowTags(item.showTag)" :key="index"
                        size="mini">
            <!-- label -->
            <template v-slot:label>
              {{ item.label }}
              <el-tooltip v-if="item.tooltip" :content="item.tooltip" class="item" effect="dark" placement="top">
                <i class="el-icon-question"></i>
              </el-tooltip>
            </template>

            <!-- 标签 -->
            <component :is="item.tag" v-model="controlProps[item.name]" v-bind="bindProps(item)">
              <ed-option-slot v-for="(option, index) of item.options"
                              :key="index"
                              :child="item.children"
                              :data="option"
                              :optionAttrs="option.attrs"
                              :tags="item.tag"
              ></ed-option-slot>

              <!-- 按钮 -->
              <el-button v-if="item.children==='el-button'" slot="append" icon="el-icon-search"
                         @click="openSelectDict"></el-button>
            </component>
          </el-form-item>
        </el-form>
      </ed-card>

      <ChooseDict ref="chooseDict" @choose="chooseCallBack"></ChooseDict>
    </div>
    <!-- 按钮区 -->
    <div class="es-drawer__footer">
      <el-button size="small" @click="cancelForm">取 消</el-button>
      <el-button :loading="loading" size="small" type="primary" @click="handleClose">
        {{ loading ? '提交中 ...' : '确 定' }}
      </el-button>
    </div>
  </el-drawer>
</template>
<script>
import {FormDesc}                         from './BaseProps'
import {controlType}                      from '../../../../../utils/setting'
import {addControlProps, getControlProps} from '../../../../../api/ds'
import {getDictItemByType}                from '../../../../../api/easyData'
import {PROPS}                            from './control'
import {getVarType}                       from "../../../../../utils/utils";
import ChooseDict                         from '../modal/ChooseDict'

export default {
  name: 'Props',
  components: {ChooseDict},
  data() {
    return {
      controlPropsVisible: false,
      loading: false,
      currentRow: {},
      propsData: {},
      controlProps: {},
      defaultForm: {},
      component: {},
      defaultFormDesc: []
    }
  },
  computed: {
    labelTooltip() {
      return `单选数据库存为${this.currentRow.controlName}:{label:'',value:''}; 多选数据库存为${this.currentRow.controlName}:[{label:'',value:''}`
    },
    showCommonProp() {
      return this.component.showCommonProp && this.component.showCommonProp.length > 0
    },
    /**
     * @name isShowTags
     * @returns {*|boolean}
     * @description 表单项条件渲染
     */
    isShowTags() {
      return (showTag) => {
        if (getVarType(showTag) === 'object') {
          return showTag.value.includes(this.controlProps[showTag.label])
        } else if (getVarType(showTag) === 'array') {
          const arr = showTag.filter(i => i.value.includes(this.controlProps[i.label]))
          return arr.length === showTag.length
        } else if (getVarType(showTag) === 'undefined') {
          return true
        }
      }
    }
  },
  methods: {
    /**
     * @name showModal
     * @param record
     * @returns {Promise<void>}
     * @description 显示弹窗
     */
    async showModal(record) {
      this.currentRow = record;
      const res = await getControlProps(record.id)

      if (res.success) {
        this.propsData = res.data;
        const {data} = res
        if (getVarType(data?.controlProps) === 'string') {
          this.controlProps = JSON.parse(data.controlProps)
          this.defaultForm = Object.assign({}, this.controlProps);
        } else {
          this.controlProps = Object.assign({})
          this.defaultForm = Object.assign({})
          if (record.controlType === 'select') {
            this.$set(this.controlProps, 'selectBindType', 'diy')
          }
          if (record.controlType === 'cascader') {
            this.$set(this.controlProps, 'cascaderBindType', 'json')
          }
        }

        this.controlPropsVisible = true;

        this.$nextTick(() => {
          this.getComponent()
        })
      } else {
        this.$message.error(res.$message)
      }
    },

    /**
     * @name getComponent
     * @description 获取渲染组件信息
     */
    getComponent() {
      if (this.currentRow.controlType) {
        let currentControl = controlType.find(item => item.value === this.currentRow.controlType);
        let component = PROPS.find(i => i.component === currentControl.component)
        if (component) {
          // 构建基础属性表单
          if (getVarType(component.showCommonProp) === 'array') {
            this.initFormDesc(component)
          }

          this.component = component
          //赋值默认值
          component.attribute.forEach(attr => {
            if (getVarType(this.controlProps[attr.name]) === 'undefined' && getVarType(attr.defaultValue) !== 'undefined') {
              this.$set(this.controlProps, attr.name, attr.defaultValue)
            }
          })
        }
      }
    },

    // 初始化表单描述
    initFormDesc(component) {
      this.defaultFormDesc = []
      FormDesc.map(desc => {
        this.defaultFormDesc.push({
          isShow: component.showCommonProp.includes(desc.prop),
          ...desc,
        })
      })
    },

    /**
     * @name bindProps
     * @param item
     * @returns {{}}
     */
    bindProps(item) {
      let props = {};

      if (item.props) {
        props = Object.assign({}, props, item.props)
      }

      if (item.tag === "ed-table-editor") {
        props.isTitle = this.controlProps.selectBindType === "diy"
      }

      return props
    },

    handleClose() {
      if (this.loading) {
        return;
      }
      this.$confirm('确定要保存控件属性吗？')
          .then(_ => {
            this.loading = true;
            let {defaultValue, validateExpression, isLabelValue} = this.defaultForm
            let controlProps = Object.assign({}, this.controlProps, {defaultValue, validateExpression, isLabelValue});
            for (let k in controlProps) {
              let value = controlProps[k];
              if (value === '' || value === null || value === undefined) {
                delete controlProps[k];
              }
            }
            if (this.currentRow.controlType === 'popup') {
              let popupObj = {}
              for (let i = 0; i < PROPS.length; i++) {
                if (PROPS[i].component === 'easydata-popup') {
                  popupObj = PROPS[i]
                  break
                }
              }
              const data = popupObj.attribute[1].options
              for (let i = 0; i < data.length; i++) {
                const item = data[i]
                if (item.value === this.controlProps.popupMode) {
                  controlProps.convertExpression = item.expression
                  break
                }
              }
            }
            let param = {
              controlId: this.currentRow.id,
              id: this.propsData?.id,
              controlProps: JSON.stringify(controlProps)
            }
            addControlProps(param).then(res => {
              if (res.success) {
                this.$message.success("保存成功");
              } else {
                this.$message.error(res.msg);
              }
            }).finally(e => {
              this.loading = false;
              this.controlPropsVisible = false;
            })
          }).catch(_ => {
      });
    },
    cancelForm() {
      this.loading = false;
      this.controlPropsVisible = false;
    },
    changeControlProps(value) {
      this.controlProps = value;
    },
    deleteRow(data) {
      this.controlProps.dataSource.splice(data.$index, 1)
    },
    openSelectDict() {
      this.$refs.chooseDict.show()
    },
    chooseCallBack(val) {
      this.$set(this.controlProps, 'dictType', val)
      getDictItemByType({type: val}).then((resp) => {
        if (resp.data) {
          let rows = [];
          for (const item of resp.data) {
            const row = {label: item.itemLabel, value: item.itemValue}
            rows.push(row)
          }
          this.$set(this.controlProps, 'dataSource', rows)
        }
      })
    },
    addItem() {
      this.controlProps.dataSource = this.controlProps.dataSource || this.$set(this.controlProps, 'dataSource', []);
      this.controlProps.dataSource.push({isChecked: false, triggerControl: ''})
    }
  }
}
</script>
<style lang="scss" scoped>
.el-table .el-form-item {
  margin-bottom: 0px
}

@import "../../../../../style/index";

.ed-card {
  margin-bottom: 10px;
}
</style>
