
<template>
  <a-modal :width="920" title="高级查询" v-bind="$props" :bodyStyle="{ padding: 0 }" :confirm-loading="confirmLoading" @ok="handleOk" @cancel="handleCancel">
    <a-layout style="height: 400px">
      <!-- <a-tooltip
        :align="{ points: ['tc', 'bc'], targetOffset: [0, 0], offset: [0, 4] }"
        :title="errorView"
        destroyTooltipOnHide
        :visible="errorView"
        :get-popup-container="getPopupContainer"
      ></a-tooltip> -->
      <a-layout-sider theme="light" width="231" class="ant-menu-inline">
        <div style="height: 100%; overflow: auto; display: flex; flex-direction: column">
          <p-button @click="addCondition" type="dashed" icon="plus" style="width: 210px; margin: 10px 10px 0">新增条件名称</p-button>

          <a-menu mode="inline" :selectedKeys="['1']" v-model="selectedKeys" :default-open-keys="['sub1']" style="overflow-y: auto; flex: 1 1; border-right-color: transparent">
            <a-menu-item style="padding-left: 28px" v-for="item in conditionNameList" :key="item.id" @mousemove="mousemove($event, item)">
              <a-row type="flex" :gutter="5" justify="space-between">
                <a-col flex="1" v-if="item.edit" :class="item.error && 'has-error'" style="position: relative">
                  <a-icon v-if="~~item.defaultFlag > -1" type="lock" style="font-size: 12px; margin-left: -19px; margin-right: 2px" />
                  <p-input type="text" :id="item.id" v-model="item.bizName" :autoFocus="true" placeholder="请输入条件名称" @pressEnter="checkEdit($event, item)" />
                </a-col>
                <a-col flex="1" v-else>
                  <a-icon v-if="~~item.defaultFlag > -1" type="lock" style="font-size: 12px; margin-left: -19px; margin-right: 2px" />
                  {{ item.bizName }}
                </a-col>

                <a-col style="width: 42px">
                  <a-space :size="3" v-show="hoverKey === item.id">
                    <a-button size="small" shape="circle" type="dashed" style="text-align: center" @click="checkEdit($event, item)">
                      <a-icon :type="item.edit ? 'check' : 'edit'" style="font-size: 12px; margin: 0px" />
                    </a-button>
                    <a-button size="small" shape="circle" type="dashed" style="text-align: center" @click="removeCondition($event, item)">
                      <a-icon type="delete" style="font-size: 12px; margin: 0px" />
                    </a-button>
                  </a-space>
                </a-col>
              </a-row>
            </a-menu-item>
          </a-menu>
        </div>
      </a-layout-sider>

      <a-layout-content style="padding: 10px; background-color: #fff">
        <!-- <p-button @click="addtableformRow">新增</p-button> -->
        <!-- :showHeader="false" -->
        <!-- :data-source.sync="tableDataform[selectedKeys[0]]" -->

        <p-table-edit-pro
          class="tableform"
          v-if="tableDataform[selectedKeys[0]]"
          row-key="hdrId"
          ref="tableform"
          :scroll="{ x: true }"
          :dataSource.sync="tableDataform[selectedKeys[0]]"
          :bordered="false"
          :rowSelectType="false"
          :hasRowCount="false"
          :columns="columns"
          :pagination="false"
          @colChange="colChange"
        >
          <template slot="operation" slot-scope="text, record">
            <a-icon @click="delFormRow(record)" data-value="assemble" :data-key="record.key" style="font-size: 16px" type="minus-circle" />
            <!-- <p-button @click="delFormRow(record)" type="danger">删除</p-button> -->
          </template>
        </p-table-edit-pro>
      </a-layout-content>
    </a-layout>

    <a-alert v-if="!!errorView" style="margin-top: -34px" type="error" :message="errorView" banner />
    <template slot="footer">
      <p-button type="primary">提交查询</p-button>
      <p-button type="primary" @click="handleSave" :disabled="conditionNameList.length === 0 || error">保存配置</p-button>
      <p-button type="primary" @click="handleDefault">设置默认</p-button>
      <p-button type="primary" @click="handleCancel">关闭</p-button>
    </template>
  </a-modal>
</template>

<script>
import { getQueryListAll, getQueryConfiguration, saveConfiguration } from './js/api.js'
import { setColumns } from './js/config'

// {
// bizName:"[string] 业务名称"
// bizType:"[string] 业务类型"
// defaultFlag:"[string] 是否默认"
// details:[
// {
// fieldCode:"[string] 字段编码"
// fieldName:"[string] 字段名称"

// fieldType:"[string] 字段类型"

// fieldValue:"[string] 字段值"
// hdrId:"[string] undefined"
// logicSymbol:"[string] 逻辑符号"
// operationSymbol:"[string] 操作符"
// seqId:"[string] 明细ID"
// seqNo:"[string] 行号"
// }
// ]
// id:"[string] 业务ID"
// }

var base = [
  {
    bizName: '默认配置5636',
    bizType: 'BtoCSalesOrder',
    defaultFlag: '0',
    details: [
      { fieldCode: 'totAmt', operationSymbol: 'isnotnull', fieldValue: '123' },
      { fieldCode: 'custContact', logicSymbol: 'and', fieldValue: '12' },
    ],
  },
]
import { createID } from '@/blocks/utils'
const defaultCondition = (bizType) => {
  return { error: false, edit: true, id: 'new-' + createID(), bizName: '', defaultFlag: 1, bizType, details: [] }
}

export default {
  name: 'advancedQueryModel',
  data() {
    return {
      // bizType,
      selectedKeys: [],
      items: [],
      selectKey: '',
      tableData: [],
      tableDataform: {},
      confirmLoading: false,
      columns: setColumns(this),
      activeKey: '',
      conditionNameList: [],
      hoverKey: '',
      errorView: false,
    }
  },
  props: {
    adQueryUrl: {
      type: String,
    },
    fieldOptions: {
      type: null,
    },

    bizType: {
      type: null,
    },
    visible: {
      type: Boolean,
      default: false,
    },
  },

  mounted() {
    //getQueryListAll(this,{ queryCode: this.queryCode })
  },
  created() {},
  watch: {
    visible(v) {
      if (v) {
        getQueryConfiguration(this, { bizType: this.bizType }).then((res) => {

        })

      }
    },
  },
  computed: {
    error() {
      if (this.conditionNameList.length > 0) {
        let error = false
        this.conditionNameList.some((item) => {
          if (!item.bizName) {
            error = true
            return false
          }
        })
        return error
      }
      return false
    },
  },
  methods: {
    handleSave() {
      let _this = this
      this.$refs.tableform.validateFields((error, values) => {
        if (error) return

        let data = []
        _this.conditionNameList.forEach((item) => {
          let { id, bizName, bizType, defaultFlag, details } = item
          if (id.indexOf('new') > -1) {
            id = ''
          }
          details.forEach((c, i) => {
            c.seqNo = i.toString()
            if (c.hdrId && c.hdrId.indexOf('new') > -1) {
              delete c.hdrId
            }
          })


          data.push({ id, bizName, bizType, defaultFlag: String(defaultFlag), details })
        })

        return saveConfiguration(this, data)
      })
    },

    handleDefault() {},
    removeCondition($event, e) {
      this.conditionNameList = this.conditionNameList.filter((item) => item.id != e.id)
      delete this.tableDataform[e.id]
      this.selectedKeys = []
    },
    checkEdit($event, item) {
      let input = this.$el.querySelector('#' + item.id)
      item.error = false
      if (input) {
        if (input.value) {
          item.bizName = input.value
        } else {
          this.getPopupContainer = () => {
            return input.parentNode
          }
          item.error = true
          this.errorView = '条件名称不能为空'
          let _this = this
          return setTimeout(() => {
            _this.errorView = ''
          }, 2000)
        }
      }
      this.tableDataform[item.id] = item.details

      item.edit = !item.edit
    },
    mousemove(event, item) {
      if (item) {
        this.hoverKey = item.id
      }
    },
    addCondition() {
      let data = defaultCondition(this.bizType)

      this.conditionNameList.unshift(data)
      this.selectedKeys = [data.id]
    },

    hideQueryModel() {
      this.$emit('hideQueryModel')
    },
    //删除行
    delFormRow(text) {
      this.$refs.tableform.removeRow(text.hdrId)
    },
    colChange({ name, record, label, value }) {
      if (name === 'fieldName') {
        record.fieldCode = value
        record.fieldName = label
      }
    },
    dblclickRow(event, activeID, rowRecord) {
      this.activeKey = activeID
      console.log(rowRecord)
    },
    clickRow(event, activeID, rowRecord) {
      console.log(rowRecord)
      this.selectKey = rowRecord.id
    },
    addRow() {
      this.$refs.table.createRow()
      this.selectKey = this.tableData[this.tableData.length - 1].id
    },
    delRow() {
      this.$refs.table.removeRow(this.selectKey)
      this.selectKey = ''
    },
    addtableformRow() {
      this.$refs.tableform.createRow()
    },
    showModal() {
      this.visible = true
    },
    handleOk(e) {
      this.ModalText = 'The modal will be closed after two seconds'
      this.confirmLoading = true
      setTimeout(() => {
        this.confirmLoading = false
        this.$emit('update:visible', false)
      }, 2000)
    },
    handleCancel(e) {
      console.log('Clicked cancel button')
      //   this.visible = false;
      this.hideQueryModel()
      this.$emit('update:visible', false)
    },
  },
}
</script>

<style lang="less" scoped>
/deep/ .tableform {
  .ant-table-placeholder {
    display: none;
  }
  .ant-table-tbody > tr > td {
    border-bottom-color: transparent;
  }
}
.menu-edit-item,
.menu-del-item {
  position: absolute;
  right: 25px;
  top: 50%;
  margin-top: -6px;
}
.menu-del-item {
  right: 0;
}
.transferBtn {
  padding: 2%;
  display: flex;
  justify-content: space-around;
}
.model {
  display: flex;
  justify-content: space-around;
}
.editTable {
  width: 29%;
}
.form {
  width: 69%;
}
</style>
