<template>
  <div style="height:75vh">
    <vxe-toolbar  ref="toolbarRef" export print custom :refresh="{ queryMethod }">
      <template #buttons >
        <vxe-button @click="batchSettingEvent()">批量设置</vxe-button>
        <vxe-button @click="expandAllEvent">展开所有</vxe-button>
        <vxe-button @click="clearExpandEvent">关闭所有</vxe-button>
      </template>
      <!-- <template #toolPrefix>
        <vxe-button status="primary" @click="refreshEvent">刷新</vxe-button>
      </template> -->
    </vxe-toolbar>
    <vxe-table
      border
      keep-source
      show-overflow
      height="auto"
      ref="tableRef"
      @cell-click="clickRowEvent"
      :export-config="{}"
      :row-config="rowConfig"
      :row-drag-config="rowDragConfig"
      :column-config="columnConfig"
      :custom-config="customConfig"
      :edit-config="{ trigger: 'dblclick', mode: 'row', showStatus: true}"
      :tree-config="treeConfig"
      :checkbox-config="{highlight: true}"
      @checkbox-change="selectChangeEvent"

      :data="tableData">

      <vxe-column type="checkbox" width="60" fixed="left">
      </vxe-column>

      <vxe-column field="pcode" title="父节点" min-width="120" tree-node>
      </vxe-column>

      <vxe-column field="title" title="标题" min-width="350"   drag-sort :edit-render="{ autofocus: '.my-input', autoselect: true }">
        <template #default="{ row }" >
          <span >{{ row.title }}</span>
        </template>
        <template #edit="{ row }">
          <vxe-textarea v-model="row.title" type="text" placeholder="请输入"  clearable  :rows="1"></vxe-textarea>
        </template> 
      </vxe-column>

      <vxe-column field="childNum" title="节点数" min-width="120"  :edit-render="{ autofocus: '.my-input', autoselect: true }">
        <template #default="{ row }" >
          <span >{{ row.childNum }}</span>
        </template>
        <template #edit="{ row }">
          <vxe-textarea v-model="row.childNum" type="text" placeholder="请输入"  clearable  :rows="1"></vxe-textarea>
        </template> 
      </vxe-column>
      
      <vxe-column field="treepathName" title="节点路径" min-width="300" :edit-render="{ autofocus: '.my-input', autoselect: true }" :visible="false">
        <template #default="{ row }" >
          <span >{{ row.treepathName }}</span>
        </template>
        <template #edit="{ row }">
          <vxe-textarea v-model="row.treepathName" type="text" placeholder="请输入"  clearable  :rows="1"></vxe-textarea>
        </template> 
      </vxe-column>

      <vxe-column field="tp" title="数值类型"  min-width="120" :edit-render="{}" >
          <template #default="{ row }">
            <span>{{ formatTp(row.tp) }}</span>
          </template>
          <template #edit="{ row }">
              <vxe-select v-model="row.tp" transfer>
              <vxe-option v-for="item in tpOptions" :key="item.value" :value="item.value" :label="item.label"></vxe-option>
            </vxe-select>
          </template>
      </vxe-column>
      
      <vxe-column field="formTp" title="表单类型"  min-width="130" :edit-render="{}" >
        <template #default="{ row }">
          <span>{{ formatFormTp(row.formTp) }}</span>
        </template>
        <template #edit="{ row }">
            <vxe-select v-model="row.formTp" transfer>
              <vxe-option v-for="item in formTpOptions" :key="item.value" :value="item.value" :label="item.label"></vxe-option>
            </vxe-select>
          </template>
      </vxe-column>
      <vxe-column field="options" title="选项" min-width="150" :edit-render="{}">
        <template #header>
          <i :class="collapsable1 ? 'vxe-icon-square-minus' : 'vxe-icon-square-plus'" @click="collapsable1Event"></i>
          <span>选项</span>
        </template>
        <template #default="{ row }">
            <span>{{ row.options }}</span>
        </template>
          <template #edit="{ row }">
              <vxe-textarea v-model="row.options" type="text" placeholder="请输入"  clearable  :rows="1"></vxe-textarea>
          </template> 
      </vxe-column>

      <vxe-column field="unit" title="单位" :visible="false" width="100" :edit-render="{ autofocus: '.my-input', autoselect: true }">
        <template #default="{ row }">
            <span>{{ row.unit }}</span>
        </template>
          <template #edit="{ row }">
            <vxe-input v-model="row.unit" type="text" placeholder="请输入"  clearable></vxe-input>
          </template> 
      </vxe-column>
      <vxe-column field="maxVal" title="最大值" :visible="false" width="100" :edit-render="{ autofocus: '.my-input', autoselect: true }">
        <template #default="{ row }">
            <span>{{ row.maxVal }}</span>
        </template>
        <template #edit="{ row }">
          <vxe-input v-model="row.maxVal" type="number" placeholder="请输入"  clearable ></vxe-input>
        </template> 
      </vxe-column>
      <vxe-column field="minVal" title="最小值" :visible="false" width="100" :edit-render="{ autofocus: '.my-input', autoselect: true }">
        <template #default="{ row }">
            <span>{{ row.minVal }}</span>
        </template>
        <template #edit="{ row }">
          <vxe-input v-model="row.minVal" type="number" placeholder="请输入"  clearable></vxe-input>
        </template> 
      </vxe-column>

      <vxe-column field="des" title="说明"  min-width="150"    :edit-render="{}" :visible="false">
        <template #default="{ row }">
            <span>{{ row.des }}</span>
        </template>
          <template #edit="{ row }">
              <vxe-textarea v-model="row.des" type="text" placeholder="请输入"  clearable  :rows="1"></vxe-textarea>
          </template> 
      </vxe-column>
      <vxe-column title="操作" min-width="200"  fixed="right" align="center">
        <template #default="{ row }">
            <template v-if="isActiveStatus(row)">
              <vxe-button @click="saveRowEvent(row)" round status="primary" mode="text">保存</vxe-button>
              <vxe-button @click="cancelRowEvent(row)" mode="text">取消</vxe-button>
            </template>
            <template v-else>
              <vxe-button round status="primary" @click="settingEvent(row)" mode="text">编辑</vxe-button>
              <vxe-button mode="text" status="primary" @click="insertRow(row)">添加节点</vxe-button>
              <vxe-button mode="text" status="primary" @click="insertChildRow(row)">添加子节点</vxe-button>
              <template v-if="row.childNum==0&&!row.code">
               <vxe-button mode="text" status="danger" @click="removeRow(row)">删除节点</vxe-button>
              </template>
            </template>
          
        </template>
      </vxe-column>
    </vxe-table>
    <vxe-modal v-model="showBatchEdit" title="批量设置" width="800" height="500" :loading="loading" resize destroy-on-close>
      <template #default>
        <vxe-form :data="formData" :rules="formRules" title-align="right" title-width="100" vertical size="medium" @submit="saveBatchSetting">
          <div style="width:100%">
          <vxe-form-item field="formTp" title="表单类型" :span="24" :item-render="{}">
              <template #default="{ data }">
                <vxe-radio-group v-model="data.formTp" size="medium">
                  <a-card>
                    <vxe-radio v-for="item in formTpOptions"  :key="item.value"  :content="item.label" :label="item.value" style="min-width:100px;margin:10px;"></vxe-radio>
                  </a-card>
                </vxe-radio-group>
              </template>
            </vxe-form-item>
            <vxe-form-item field="tp" title="数值类型" :span="24" :item-render="{}">
              <template #default="{ data }">
                <vxe-radio-group v-model="data.tp" size="medium">
                  <a-card>
                    <vxe-radio v-for="item in tpOptions"  :key="item.value"  :content="item.label" :label="item.value" style="min-width:100px;margin:10px;"></vxe-radio>
                  </a-card>
                </vxe-radio-group>
              </template>
            </vxe-form-item>
            <vxe-form-item align="center" :span="24">
              <template #default>
                <vxe-button type="submit">提交</vxe-button>
                <vxe-button type="reset">重置</vxe-button>
              </template>
            </vxe-form-item>
          </div>
        </vxe-form>
      </template>
    </vxe-modal>

    <vxe-modal
      resize
      destroy-on-close
      show-footer
      show-confirm-button
      show-cancel-button
      v-model="showEdit"
      title="编辑"
      width="50vw"
      height="60vh"
      :loading="loading"
      :confirm-closable="false"
      @confirm="confirmEvent">
      <vxe-form ref="formRef" v-bind="formOptions"></vxe-form>
    </vxe-modal>

  </div>
</template>

<script lang="ts" setup>
import { ref,reactive,onMounted,nextTick,computed  } from 'vue'
import { getAuthCache } from '/@/utils/auth';
import {VxeUI,VxeTableEvents,VxeFormPropTypes,VxeTablePropTypes,VxeFormProps,VxeFormItemPropTypes,VxeSelectProps} from 'vxe-table'
import { allTplItems,saveOrUpdate,saveBatch,deleteOne } from '../BaosongTplItem.api';
import XEUtils from 'xe-utils'

interface RowVO {
  id: number|null
  title: string
  tp: number|null
  pcode: string
  code: string
  childNum: number|null
  hasChild?: boolean|null
  formTp?:number|null
  treepathName?:string|null
  pid:number|null
  tplid:number|null
  tplName:string|null
  unit:string|null
  maxVal:number|null
  minVal:number|null
}


const defaultData: RowVO = {
  id: null,
  title: "",
  tp: null,
  pcode: "",
  code: '',
  childNum: null,
  hasChild: false,
  formTp:null,
  treepathName:null,
  pid:null,
  tplid:null,
  tplName:'',
  unit:'',
  maxVal:null,
  minVal:null,
}

const formData = reactive({
  itemids:[],
  formTp: '',
  tp: '',
  des:''
})

const formRules = reactive<VxeFormPropTypes.Rules>({
  formTp: [
    { required: true, message: '请选择表单类型' }
  ],
  tp: [
    { required: false, message: '请选择数值类型' }
  ]
})

const curTpl = ref()
const loading = ref(false)
const tableRef = ref()
const tableData = ref<RowVO>({})
const formTpOptions = ref([{}])
const showBatchEdit = ref(false)

const collapsable1 = ref(false)

const formRef = ref()

const showEdit = ref(false)

const toolbarRef = ref()
const tpOptions = ref([])

const customConfig = reactive<VxeTablePropTypes.CustomConfig>({
  mode: 'modal'
})


const queryMethod = async () => {
  loading.value = true;
  try {
    const tplData = curTpl.value;
    tableData.value = await allTplItems({ tplid: tplData.id });
  } catch (error) {
    console.error("刷新数据失败:", error);
  } finally {
    loading.value = false;
  }
};


async function setData(tplData){
  if(!tplData){
    tplData = curTpl.value
  }

  loading.value =true
  curTpl.value = tplData
  tableData.value = await allTplItems({tplid:tplData.id});
  await setFormTpOptions();
  loading.value =false
}

function getSelectIds() {
    let ids = [];
    const $table = tableRef.value;
    if ($table) {
      const selRecords = $table.getCheckboxRecords();
      selRecords.forEach(function (ele) {
        ids.push(ele.id);
      });
    }
    return ids;
  }

  function getSelectDatas() {
    const $table = tableRef.value;
    const selRecords = $table?.getCheckboxRecords();
    return selRecords;
  }

  const selectChangeEvent: VxeTableEvents.CheckboxChange<RowVO> = ({ $table }) => {
    const records = $table.getCheckboxRecords()
    return records;
  }

  const isActiveStatus = (row: RowVO) => {
    const $table = tableRef.value
    if ($table) {
      return $table.isEditByRow(row)
    }
  }

  const editRowEvent = (row: RowVO) => {
  const $table = tableRef.value
  if ($table) {
    $table.setEditRow(row)
  }
}

const saveRowEvent =  (row: RowVO) => {
  const $table = tableRef.value
  if($table) {
    $table.clearEdit().then(async() => {
      loading.value = true
      await saveOrUpdate(row, row.id?true:false)
      loading.value = false
    })
  }
}

const cancelRowEvent = (row: RowVO) => {
  const $table = tableRef.value
  if ($table) {
    $table.clearEdit().then(() => {
      $table.revertData(row)
    })
  }
}


const formatFormTp = (val) => {
  if (val) {
    let option = formTpOptions.value.find(item=>item.value== val)
    return option?.label
  }
  return ''
}

const formatTp = (val) => {
  if (val) {
    let option = tpOptions.value.find(item=>item.value== val)
    return option?.label
  }
  return ''
}

async function setFormTpOptions() {
  let allDict = await getAuthCache("UI_CACHE_DB_DICT_DATA") 
  formTpOptions.value  = allDict["fxc_form_tp"] 
  tpOptions.value  = allDict["fxc_value_tp"] 
}


const batchSettingEvent =  () => {
  formClear()
  const $table = tableRef.value
  if($table) {
    let datas = getSelectDatas();
    if(datas.length==0) {
      VxeUI.modal.message({ content: '请选择模板项', status: 'warning' });
      return
    }
    showBatchEdit.value = true
  }
}

const clickRowEvent = (params) => {
    const { row, column, rowIndex, columnIndex, $event } = params;  
    if(!column.field) return
    //editRowEvent(row);
  };


async function saveBatchSetting() {
    formData["itemids"]  = await getSelectIds();
    if(!formData["formTp"]) {
      return 
    }
    await saveBatch(formData)
    showBatchEdit.value = false
}

function formClear() {
  formData.itemids=[]
  formData.tp=""
  formData.formTp=""
}


async function insertRow(currRow) {
  const $table = tableRef.value;
  let record: RowVO = {
    id: 0,
    title: '',
    tp: 0,
    tplName: currRow.tplName,
    tplid: currRow.tplid,
    treepathName: currRow.treepathName + "/",
    pid: currRow.pid,
    pcode: '',
    code: '',
    childNum: 0,
    hasChild: false
  };

  const { row:newRow } = await $table.insertAt(record, currRow)
  await $table.setEditRow(newRow)
}

async function insertChildRow(currRow) {
  const $table = tableRef.value;
  let record: RowVO = {
    id: 0,
    title: '',
    tplName: currRow.tplName,
    tplid: currRow.tplid,
    treepathName: currRow.treepathName + "/",
    tp: 0,
    pid: currRow.id,
    pcode: '',
    code: '',
    childNum: 0,
    hasChild: false
  };

  // currRow.hasChild = true;
  // currRow.childNum++;

  const { row: newRow } = await $table.insertAt(record, -1)
  await $table.setTreeExpand(currRow, true) // 将父节点展开
  await $table.setEditRow(newRow) //

}


const rowConfig = reactive<VxeTablePropTypes.RowConfig<RowVO>>({
  drag: true
})


const rowDragConfig = reactive<VxeTablePropTypes.RowDragConfig<RowVO>>({
  isCrossDrag: true,
  isSelfToChildDrag: true,
  isToChildDrag: true,
  showGuidesStatus: true,
  async dragEndMethod(event) {
    const { newRow, oldRow, dragRow, dragPos } = event;

    const type = await VxeUI.modal.confirm({
      content: '是否确认调整顺序？'
    });

    if (type === 'confirm') {
      if (dragPos === "top") {
        dragRow.pid = newRow.pid; 
      } else {
        dragRow.pid = newRow.id;
      }

      // 保存拖拽节点
      const retRow = await saveOrUpdate(dragRow, !!dragRow.id);

      if (dragPos === "bottom") {
        const $table = tableRef.value;
        if ($table) {
          //await $table.setTreeExpand(newRow, true);
          if (!newRow.hasChild) {
            newRow.hasChild = true;
            newRow.childNum = 1;
            const { row: newDragRow } = await $table.insertAt(retRow, -1)
            //newRow.children =[newDragRow];
            nextTick(async ()=>{
              await $table.setTreeExpand(newRow, true) 
              await $table.remove(dragRow)
              await $table.setEditRow(newDragRow)
            })
           
          } else {
            //newRow.children?.push(retRow);
            const { row: newDragRow } = await $table.insertAt(retRow, -1)
             await $table.setEditRow(newDragRow)
          }
        }
      }
      return true;
    } else {
      VxeUI.modal.message({
        content: '操作已取消',
        status: 'warning'
      });
      return false;
    }
  }
});

const columnConfig = reactive<VxeTablePropTypes.ColumnConfig<RowVO>>({
    resizable:true,
    drag:true,
})


const removeRow = async (row: RowVO) => {
  const $table = tableRef.value
  if ($table) {
    await $table.remove(row)
    await deleteOne({id:row.id},function(){
      console.log("删除成功")
    })
  }
}

const toggleExpandChangeEvent = (params: any) => {
  const $table = tableRef.value
  if ($table) {
    const { row, expanded } = params
    console.log('节点展开事件', expanded, '获取父节点：', $table.getParentRow(row))
  }
}

const getTreeExpansionEvent = () => {
  const $table = tableRef.value
  if ($table) {
    const treeExpandRecords = $table.getTreeExpandRecords()
    VxeUI.modal.alert(treeExpandRecords.length)
  }
}

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

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


const treeConfig = reactive<VxeTablePropTypes.TreeConfig<RowVO>>({
  transform: true,
  rowField: 'id',
  parentField: 'pid',
  lazy: true,
  hasChild: 'hasChild',
})


onMounted(() => {
  const $table = tableRef.value
  const $toolbar = toolbarRef.value
  if ($table && $toolbar) {
    $table.connect($toolbar)
  }
})


const curEditRow = ref()
const settingEvent = (row) => {
  curEditRow.value = row
  formClear()
  const $table = tableRef.value
  if($table) {
    showEdit.value = true
    formOptions.data = Object.assign(XEUtils.clone(defaultData, true), row)
  }
}


const collapsable1Event = () => {
  const $table = tableRef.value
  if ($table) {
    const fields = ['unit','maxVal','minVal']
    collapsable1.value = !collapsable1.value
    fields.forEach(field => {
      if (collapsable1.value) {
        $table.showColumn(field)
      } else {
        $table.hideColumn(field)
      }
    })
  }
}

const tpItemRender = computed(() => ({
  name: 'VxeSelect',
  options: tpOptions.value,
}));

const formTpItemRender = computed(() => ({
  name: 'VxeSelect',
  options: formTpOptions.value,
}));


const formOptions = reactive<VxeFormProps<RowVO>>({
  titleWidth: 100,
  titleAlign: 'right',
  titleColon: true,
  data: XEUtils.clone(defaultData, true),
  rules: {
    title: [
      { required: true, message: '标题' },
      { min: 1, max: 64, message: '长度在 1 到 64 个字符' }
    ],
    tp: [
      { required: true, message: '数值类型' }
    ],
    formTp: [
      { required: true, message: '表单类型' },
    ],
    age: [
      { required: true, message: '请输入年龄' }
    ]
  },
  items: [
    { field: 'title', title: '标题', span: 12, itemRender: { name: 'VxeInput' } },
    { field: 'tp', title: '数值类型', span: 12, itemRender: tpItemRender},
    { field: 'formTp', title: '表单类型', span: 12, itemRender: formTpItemRender},

    { field: 'unit', title: '单位', span: 12, itemRender: { name: 'VxeInput' } },
    { field: 'maxVal', title: '最大值', span: 12, itemRender: { name: 'VxeInput' } },
    { field: 'minVal', title: '最小值', span: 12, itemRender: { name: 'VxeInput' } },
    
    { field: '', title: '异动阈值', span: 12, itemRender: { name: 'VxeInput' } },

    { field: 'options', title: '选项', span: 24, itemRender: { name: 'VxeTextarea', props: { autosize: { minRows: 5, maxRows: 6 } } } },

    { field: 'des', title: '填报说明', span: 24, itemRender: { name: 'VxeTextarea', props: { autosize: { minRows: 5, maxRows: 6 } } } },
    
  ]
})


const confirmEvent = async () => {
  const $form = formRef.value
  if ($form) {
    const errMap = await $form.validate()
    if (!errMap) {
      const formData = formOptions.data;
      showEdit.value = false
      await saveOrUpdate(formData,true)
      Object.assign(curEditRow.value, formData);
      VxeUI.modal.message({ content: '保存成功', status: 'success' })
    }
  }
}

 
defineExpose({
  setData,
  getSelectDatas,
  getSelectIds
});
</script>




