<template>
  <vxe-drawer
    destroy-on-close
    show-footer
    title="设置公式"
    v-model="showEditPopup"
    width="100%"
    height="100%"
    :loading="loading"
    :confirm-closable="false"
    show-confirm-button
    show-cancel-button
    style="padding:0px"
    @confirm="confirmEvent">
      
    <a-row :gutter="6" style="height: calc(100% - 10px);background-color:#FFF;padding:0px;margin:0px">
      <a-col class="gutter-row" :span="10" style="height: 100%;">
        <a-card style="height:100%;" :bodyStyle="{height:'100%'}">
          <vxe-grid ref= "gridRef" 
              v-bind="gridOptions"
              v-on="gridEvents" 
              @checkbox-change="setFormula"
              >
                <template #titleHeader="{ column }">
                  <div v-for="(option, index) in column.filters" :key="index">
                    <vxe-input v-model="option.data" clearable @change="confirmFilterEvent(option)" style="width: 100%;"></vxe-input>
                  </div>
                </template>

                <template #tplHeader="{ column }">
                  <div v-for="(option, index) in column.filters" :key="index">
                    <vxe-select v-model="option.data" :options="tplDatas" clearable @change="confirmFilterEvent(option)" style="width: 100%;"></vxe-select>
                  </div>
                </template>

                <template #toolbarButtons>
                      模板项目列表
                      <vxe-button mode="text" size="small" @click="expandAllEvent">展开所有</vxe-button>
                      <vxe-button mode="text" size="small"@click="clearExpandEvent">关闭所有</vxe-button>
                </template>
                
          </vxe-grid>
        </a-card>
      </a-col>
      <a-col class="gutter-row" :span="7">
        <!-- 已选项目卡片 - 占50%高度 -->
        <a-card class="gutter-box selected-items" title="已选项目">
          <vxe-table
            :data="selTplItems"Header
            :showHeader="false"
            height="auto">
            <vxe-column field="title" title="名称"></vxe-column>
            <vxe-column field="code" title="编码" width="120"></vxe-column>
            <vxe-column title="操作" width="80">
            <template #default="{ row }">
              <vxe-button mode="text" @click="insertParams(row)" icon="vxe-icon-arrow-right">
              </vxe-button>
            </template>
          </vxe-column>
          </vxe-table>
        </a-card>
      
        <!-- 验证规则描述卡片 - 占50%高度 -->
        <a-card class="gutter-box validation-description" title="验证规则描述">
          <vxe-textarea 
            v-model="formData.des" 
            style="height: 100%; width: 100%;" 
            :autosize="{minRows: 1}">
          </vxe-textarea>
        </a-card>
      </a-col>
      <a-col class="gutter-row" :span="7">
 
        <a-card class="gutter-box" style="height:100%" title="验证公式">
          <div style="margin: 5px;">
            <vxe-select v-model="formData.tplItemid" placeholder="" size="mini" :clearable="true">
              <vxe-option v-for="item in selTplItems" :key="item.id" :value="item.id" :label="item.title"></vxe-option>
            </vxe-select>
          </div>
          <div style="height: 150px;margin: 5px;">
            <vxe-textarea ref="refFormula" v-model="formData.formula" placeholder="请输入验证公式" :autosize="{minRows: 4, maxRows: 6}" clearable>
            </vxe-textarea>
          </div>
          
          <div :style="{ background: '', padding: '16px 16px' }">
            <a-space>
              <a-button type="primary" ghost @click="insertOperator('+')">加[+]</a-button>
              <a-button type="primary" ghost @click="insertOperator('-')">减[-]</a-button>
              <a-button type="primary" ghost @click="insertOperator('*')">乘[*]</a-button>
              <a-button type="primary" ghost @click="insertOperator('/')">除[/]</a-button>
              <a-button type="primary" ghost @click="insertOperator('%')">取余[%]</a-button>
            </a-space>
          </div>

          <div :style="{ background: '', padding: '16px 16px' }">
            <a-space>
              <a-button type="primary" ghost  @click="insertOperator('\(')">左括号[(]</a-button>
              <a-button type="primary" ghost  @click="insertOperator('\)')">右括号[)]</a-button>
              <a-button type="primary" ghost  @click="insertOperator('=')">赋值[=]</a-button>
              <a-button type="primary" ghost  @click="insertOperator('==')">等于[==]</a-button>
            </a-space>
          </div>

          <div :style="{ background: '', padding: '16px 16px' }">
            <a-space>
              <a-button type="primary" ghost @click="insertOperator('||')">不等于[!=]</a-button>
              <a-button type="primary" ghost @click="insertOperator('>')">大于[>]</a-button>
              <a-button type="primary" ghost @click="insertOperator('<')">小于[<]</a-button>
              <a-button type="primary" ghost @click="insertOperator('>=')">不小于[>=]</a-button>
            </a-space>
          </div>
          <div :style="{ background: '', padding: '16px 16px' }">
            <a-space>
              <a-button type="primary" ghost @click="insertOperator('<=')">不大于[<=]</a-button>
              <a-button type="primary" ghost @click="insertOperator('&&')">与[&&]</a-button>
              <a-button type="primary" ghost @click="insertOperator('||')">或[||]</a-button>
              <a-button type="primary" ghost @click="insertOperator('!')">非[!]</a-button>
            </a-space>
          </div>


          <div :style="{ background: '', padding: '16px 16px' }">
            <a-space>
              <a-button type="primary" ghost  @click="insertOperator('0')">0</a-button>
              <a-button type="primary" ghost  @click="insertOperator('1')">1</a-button>
              <a-button type="primary" ghost  @click="insertOperator('2')">2</a-button>
              <a-button type="primary" ghost  @click="insertOperator('3')">3</a-button>
              <a-button type="primary" ghost  @click="insertOperator('4')">4</a-button>
              <a-button type="primary" ghost  @click="insertOperator('5')">5</a-button>
              <a-button type="primary" ghost  @click="insertOperator('6')">6</a-button>
            
            </a-space>
          </div>
          <div :style="{ background: '', padding: '16px 16px' }">
            <a-space>
              <a-button type="primary" ghost  @click="insertOperator('7')">7</a-button>
              <a-button type="primary" ghost  @click="insertOperator('8')">8</a-button>
              <a-button type="primary" ghost  @click="insertOperator('9')">9</a-button>
              <a-button type="primary" ghost  @click="insertOperator('%')">%</a-button>
              <a-button type="primary" ghost  @click="insertOperator('100%')">100%</a-button>
            </a-space>
          </div>
        </a-card>
      </a-col>
    </a-row>
      
  </vxe-drawer>
</template>

<script lang="ts" setup>
import { ref, nextTick, reactive, computed } from 'vue'
import type { VxeGridProps, VxeGridListeners, VxeGridInstance } from 'vxe-table'
import { VxeUI, VxeTextareaInstance } from 'vxe-pc-ui'

import { allTplItems } from '../BaosongTplItem.api'
import { allTpls } from '../BaosongTpl.api'
import { saveOrUpdate } from '../BaosongDataValid.api'
import { itemFormSchema } from '/@/views/system/dict/dict.data'
import { Item } from 'ant-design-vue/es/menu'

interface TplItem {
id: number
pid: number | null
code: string
pcode:string
title: string
tp:number
}

const emit = defineEmits(['success']);


const formData = reactive<any>({
id:'',
code: '',
name: '',
params: '',
formula: '',
des: '',
tp:'' ,
tplid:'',
tplItemid:''
})

const showEditPopup = ref(false)
const loading = ref(false)
const curDataValid = ref<any>({})
const gridRef = ref<VxeGridInstance>()
const refFormula = ref<VxeTextareaInstance>()


const tplDatas = ref<Array<{ label: string; value: any }>>([]);

// const selectedItemsText = computed(() => {
//   return selTplItems.value.map(item => `${item.title} [${item.code}]`).join('\n')
// })

const selTplItems = ref<TplItem[]>([])

const gridOptions = reactive<VxeGridProps>({
border: true,
treeConfig: {
  transform: true,
  rowField: 'code',
  parentField: 'pcode'
},
height: "auto",
checkboxConfig: {
  checkStrictly: true,
  highlight: true,
},
filterConfig: {
  showIcon: false
},
rowConfig: {
  isCurrent: true,
  isHover: true,
  resizable:true
},


columnConfig: {
  useKey: true,
  resizable:true
},

toolbarConfig: {
  custom: true,
  zoom: true,
  slots: {
    buttons: 'toolbarButtons',
    tools: 'toolbarTools'
  }
},
columns: [
  { field:'code',title:'编码',width:'25%', treeNode: true},
  { type: 'checkbox',width:'50',title:'选择'},
  { title: '模板', width:'20%', sortable: true,
    children: [
      {
        field: 'tplName',
        width: 200,
        formatter ({ cellValue }) {
          const item = tplDatas.value.find(item => item.value === cellValue)
          return item ? item.label : ''
        },
        filters: [
          { data: '' }
        ],
        filterMethod ({ option, row, column }) {
          if (option.data) {
            return row[column.field] === option.data
          }
          return true
        },
        slots: {
          header: 'tplHeader'
        }
      }
    ]
  },
  {
    title:'节点名称',
    sortable: true,
    children: [
      {
        field: 'title',
        filters: [{ data: '' }],
        filterMethod({ option, row, column }) {
          if (option.data) {
            return `${row[column.field]}`.indexOf(option.data) > -1
          }
          return true
        },
        slots: {
          header: 'titleHeader'
        }
      }
    ]
  },
],
data: []
})

const gridEvents: VxeGridListeners = {
cellClick({ row }) {
  // const $table = gridRef.value
  // if ($table) {
  //   $table.toggleCheckboxRow(row)
  //   setFormula({ row })
  // }
}
}

const confirmFilterEvent = (option: { data: string }) => {
  const $grid = gridRef.value
  if ($grid) {
    $grid.updateFilterOptionStatus(option, !!option.data)
    $grid.updateData();
    nextTick(()=>{
      $grid.setAllTreeExpand(true)
    })
  }
}

const confirmEvent = async () => {

  try {
    const isUpdate = !!curDataValid.value?.id
    loading.value = true

    formData.tplid =  selTplItems.value[0]?.tplid
    await saveOrUpdate(formData, isUpdate)
    //VxeUI.modal.message({ content: '保存成功', status: 'success' })
    //showEditPopup.value = false
    emit("success")

    Object.keys(formData).forEach(key => {
      formData[key] = '';
    });

    selTplItems.value = [];

  } catch (error) {
    VxeUI.modal.message({ content: '保存失败', status: 'error' })
  } finally {
    loading.value = false
  }
}


const setData = async (validTp, dataValid) => {

Object.keys(formData).forEach(key => {
  formData[key] = '';
});
if (dataValid) {
  Object.assign(formData, dataValid);
}
formData.tp = validTp;
showEditPopup.value = true;
curDataValid.value = dataValid;
selTplItems.value = [];

try {
  loading.value = true;
  const allTplDatas = await allTpls({});
 
  tplDatas.value = allTplDatas.map(item => ({
    label: item.nm,
    value: item.nm,
  }));

  allTplDatas.forEach(item => {
    item.title = item.nm;
    item.tplcode =  item.code.replace(/-/g, '_');
    item.tplName = item.nm;
    item.code = item.code.replace(/-/g, '_');
    item.tplid=item.id
  });

  const tplItems = await allTplItems({});
  gridOptions.data = allTplDatas.concat(tplItems);
  
  if (formData.params) {
    const selectedCodes = formData.params.split(',');
    await nextTick();
    const $table = gridRef.value;
    if ($table) {
      const rowsToSelect = tplItems.filter(row => 
        selectedCodes.includes(row.id.toString()) 
      );
      
      if (rowsToSelect.length > 0) {
        $table.setCheckboxRow(rowsToSelect, true);
        selTplItems.value = rowsToSelect;
      }

      const nodesToExpand = new Set();
      rowsToSelect.forEach(row => {
        const findParents = (node) => {
          if (node.pcode) {
            const parent = gridOptions.data.find(r => r.code === node.pcode);
            if (parent) {
              nodesToExpand.add(parent);
              findParents(parent); 
            }
          }
        };
        findParents(row);
      });

      nodesToExpand.forEach(node => {
        $table.setTreeExpand(node, true);
      });
      rowsToSelect.forEach(row => {
        $table.setTreeExpand(row, true);
      });

    }
  }
} catch (error) {
  console.error('Error loading template items:', error);
  VxeUI.modal.message({ content: '加载模板项目失败', status: 'error' });
} finally {
  loading.value = false;
}
};

const setFormula = () => {
const selRows = getSelectDatas();
formData.params = selRows.map(item => item.id).join(',')
selTplItems.value = selRows
}

const getSelectDatas = (): TplItem[] => {
const $table = gridRef.value
return $table ? $table.getCheckboxRecords(true) : []
}

const insertParams=(item)=>{
insertOperator(item.code + " ");
}

const insertOperator = (operator: string) => {
const textarea = refFormula.value
if (!textarea) return
const textareaEl = textarea.$el.querySelector('textarea')
if (!textareaEl) return
const startPos = textareaEl.selectionStart
const endPos = textareaEl.selectionEnd
const currentValue = formData.formula
formData.formula = currentValue.substring(0, startPos) +  operator +  currentValue.substring(endPos)

nextTick(() => {
  textareaEl.selectionStart = textareaEl.selectionEnd = startPos + operator.length
  textareaEl.focus()
})
}

const expandAllEvent = () => {
const $table = gridRef.value
if ($table) {
  $table.setAllTreeExpand(true)
}
}

const clearExpandEvent = () => {
const $table = gridRef.value
if ($table) {
  $table.clearTreeExpand()
}
}

defineExpose({
setData,
})
</script>

<style scoped>
blockquote {
  padding: 0px 5px;
  color: black;
  cursor: pointer;
}

.gutter-row {
  display: flex;
  flex-direction: column;
  height: 100%;

}

.wrap-button {
  width: 100%;
  margin: 2px;
  text-align: left;
  white-space: normal; 
  word-break: break-all; 
}


.gutter-box {
  flex: 1;
  display: flex;
  flex-direction: column;
}


.selected-items {
  flex: 0 0 50%;
  margin-bottom: 6px; 
}

.validation-description {
  flex: 0 0 50%;
}
.gutter-box ::v-deep .ant-card-body {
  padding: 0;
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
.gutter-box ::v-deep .vxe-table {
  margin: 0;
  border: none;
  flex: 1;
  height: auto !important;
}

.gutter-box ::v-deep .vxe-table--render-wrapper {
  height: 100% !important;
}

.gutter-box ::v-deep .vxe-table--body-wrapper {
  overflow-y: auto;

}

.gutter-box ::v-deep .vxe-textarea {
  height:100% !important;
}

.gutter-box ::v-deep .vxe-textarea .vxe-textarea--inner {
  height: 100% !important;
  resize: none;
}


</style>
