<template>
  <div style="padding-bottom:5px">
    <el-tag type="info">可编辑 / 总字段数</el-tag>
    <span>&nbsp;</span>
    <el-tag type="success">{{ tableNames.length }} / {{ allTableCount }}</el-tag>
    <span>&nbsp;&nbsp;&nbsp;</span>
    <el-select v-model="dbradio"
               placeholder="选择数据表"
               size="small"
               @change="dbchange"
               style="width: 120px">
      <el-option v-for="item in dblist"
                 :key="item.value"
                 :label="item.label"
                 :value="item.value" />
    </el-select>
  </div>

  <div>
    <div class="container">
      <el-table :data="tableNames" border style="width: 100%; z-index: 0;" empty-text="暂无可变更字段">
        <el-table-column label="操作" width="75">
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <t-button variant="text"
                        shape="square"
                        size="extra-small"
                        v-if="!scope.row.del"
                        @click="openUpdateDialog(scope.row)">
                <template #icon>
                  <t-icon size="20px" name="task-checked-1" v-if="scope.row.edit" />
                  <t-icon size="20px" name="edit" v-else />
                </template>
              </t-button>
              <span v-if="!scope.row.del" style="font-size:10px">|</span>
              <t-button variant="text"
                        shape="square"
                        size="extra-small"
                        v-if="!scope.row.del"
                        @click="openDelDialog(scope.row)">
                <template #icon>
                  <t-icon size="20px" name="delete-1" />
                </template>
              </t-button>
              <t-button variant="text"
                        shape="square"
                        size="extra-small"
                        v-if="scope.row.del"
                        @click="retrunDelDialog(scope.row)">
                <template #icon>
                  <t-icon size="20px" name="rollback" />
                </template>
              </t-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="字段名" width="123">
          <template #default="scope">
            <div v-if="scope.row.edit">
              <t-input placeholder="字段名" v-model="scope.row.name" style="padding:1px;height:33px" borderless />
            </div>
            <div v-else-if="!scope.row.id" style="color:green"><strong>{{scope.row.name}}</strong></div>
            <div v-else-if="scope.row.del" style="color:gray"><del>{{scope.row.name}}</del></div>
            <div v-else-if="scope.row.old" style="color:blue"><u>{{scope.row.name}}</u></div>
            <div v-else>{{scope.row.name}}</div>
          </template>
        </el-table-column>
        <el-table-column label="备注" width="140">
          <template #default="scope">
            <div v-if="scope.row.edit">
              <t-input placeholder="备注" v-model="scope.row.notes" style="padding:1px;height:33px" borderless />
            </div>
            <div v-else>
              {{scope.row.notes}}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="类型" width="100">
          <template #default="scope">
            <div v-if="scope.row.edit">
              <!--<t-input placeholder="类型" v-model="scope.row.type" style="padding:1px;height:40px" borderless />-->
              <el-select v-model="scope.row.type">
                <el-option v-for="item in typeList" :key="item" :label="item" :value="item" placeholder="类型" />
              </el-select>
            </div>
            <div v-else>
              {{scope.row.type}}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="长度" width="75">
          <template #default="scope">
            <div v-if="scope.row.edit">
              <div v-if="scope.row.type == 'varchar'">
                <t-input placeholder="长度" v-model="scope.row.long" style="padding:1px;height:33px" borderless type="number" />
              </div>
              <div v-else>\</div>
            </div>
            <div v-else>
              <span v-if="scope.row.long">{{scope.row.long }}</span>
              <span v-else>\</span>
            </div>
          </template>
        </el-table-column>
      </el-table>

    </div>
    <!-- 新增 悬浮按钮 -->
    <t-fab :icon="iconFuncAdd"
           draggable="true"
           style="bottom: 100px;"
           @click="openCreateDialog"
           class="fab-button" />
    <!--    <t-fab :icon="iconFuncSave"
               draggable="true"
               style="bottom: 45px;"
               @click="saveDialog"
               class="fab-button" />-->
    <!-- 确认删除对话框 -->
    <t-dialog v-model:visible="delDialogVisible"
              cancel-btn="取消"
              :confirm-btn="{ content: '确认删除', theme: 'danger' }"
              @confirm="delRow">
      <!--<div v-if="currentTable.id">是否确认加入删除清单？（可撤回）</div>
      <div v-if="!currentTable.id">是否确认永久删除？（不可撤销）</div>-->
      <div>是否确认永久删除？（不可撤销）</div>
    </t-dialog>
    <t-dialog v-model:visible="newDialogVisible"
              cancel-btn="取消"
              :confirm-btn="{ content: '确认保存', theme: 'danger' }"
              @confirm="saveDialog">
      <!--<div v-if="currentTable.id">是否确认加入删除清单？（可撤回）</div>
      <div v-if="!currentTable.id">是否确认永久删除？（不可撤销）</div>-->
      <div>是否确认保存修改？（不可撤销）</div>
    </t-dialog>
    <!-- 保存确认 -->
    <t-dialog v-model:visible="editDialogVisible"
              cancel-btn="取消"
              :confirm-btn="{ content: '确认提交', theme: 'danger' }"
              @confirm="saveChanges">
      <div style="color:red;font-size:18px">操作不可逆, 是否确定提交?</div>
      <br />
      <!-- 新增 -->
      <div>
        <div style="color:blue" v-if="addList.length > 0">新增字段</div>
        <!--<div style="color:blue" v-else>无新增字段</div>-->
        <span v-for="item in addList" style="white-space: nowrap;">{{ item.name }}&nbsp;&nbsp;</span>
      </div>

      <!-- 修改 -->
      <div>
        <div style="color:green" v-if="updateList.length > 0">修改字段</div>
        <!--<div style="color:green" v-else>无修改字段</div>-->
        <span v-for="item in updateList" style="white-space: nowrap;">{{ item.name }}&nbsp;&nbsp;</span>
      </div>

      <!-- 删除 -->
      <div>
        <div style="color:gray" v-if="delList.length > 0">删除字段</div>
        <!--<div style="color:gray" v-else>无删除字段</div>-->
        <span v-for="item in delList" style="white-space: nowrap;">{{ item.name }}&nbsp;&nbsp;</span>
      </div>

    </t-dialog>
  </div>


</template>


<script setup>
  import { ref, reactive, onMounted, watch, inject, h } from 'vue';
  import { Toast } from 'tdesign-mobile-vue';
  import { AddIcon, SaveIcon } from 'tdesign-icons-vue-next';

  const $http = inject('$http')
  // 初始化加载数据
  onMounted(() => {
    getTable()
  });
  const allTableCount = ref(0)

  const dbradio = ref('tbl_snlist');
  const dblist = ref([
    {
      value: "tbl_snlist",
      label: "snlist"
    },
    {
      value: "tbl_importinfo",
      label: "importinfo"
    }
  ])


  const dbchange = (val) => {
    dbradio.value = val
    getTable()
  }

  const typeList = ref([
    "varchar",
    "int",
    "tinyint",
    "bigint",
    "double",
    "datetime",
    "text",
  ])
  const iconFuncAdd = () => h(AddIcon, { size: '24px' });
  const iconFuncSave = () => h(SaveIcon, { size: '24px' });
  const tableNames = ref([]);
  var currentTable = reactive({
    id: null,
    name: '',
    notes: '',
    type: '',
    long: null,
    old: null,
    del: false,
    edit: false,
  })


  // 获取数据库表
  const getTable = () => {
    let requestBody = {
      key: "getTable",
      CmdType: "sys",
      DBQueryData: [
        {
          key: "@DBName",
          value: localStorage.getItem('selectdb'),
          valueType: "string",
        },
        {
          key: "@TBName",
          value: dbradio.value,
          valueType: "string",
        }
      ]
    }

    const dbtb = localStorage.getItem('selectdb')
    //console.log(requestBody)
    $http.post('DataHandle/R_InfoCommon', requestBody)
      .then(rs => {
        //console.log(rs)
        if (rs.data.isok) {
          allTableCount.value = rs.data.response.length
          tableNames.value = []
          let tbexclude = 0
          if (dbradio.value == 'tbl_snlist') {
            tbexclude = 34
          } else if (dbradio.value == 'tbl_importinfo') {
            tbexclude = 9
          }
          rs.data.response.forEach((item, index) => {
            if (index >= tbexclude) {
              tableNames.value.push({
                id: index + 1,
                name: item.name,
                type: item.type,
                notes: item.notes,
                long: Object.prototype.toString.call(item.long) === '[object Number]' ? item.long : null,
                edit: false,
                old: null,
                del: false,
              })
            }
          });

          //console.log(tableNames.value)
        } else {
          Toast(rs.data.message)
        }
      })
      .catch(error => {
        // 处理错误情况
        console.error(error);
      })
      .finally(() => {

      })
  }

  // 确认保存
  const saveDialog = () => {
    addList.value = []
    delList.value = []
    updateList.value = []
    tableNames.value.forEach((item, index) => {
      if (item.id == null) { // 新增
        addList.value.push(item)
        //addUts(item)
      } else if (item.del) { // 删除
        delList.value.push(item)
        //delUts(item)
      } else if (item.old) { // 更新
        updateList.value.push(item)
        //updateUts(item)
      }
    });
    editDialogVisible.value = true
  }

  const editDialogVisible = ref(false);
  // 新增行
  const openCreateDialog = () => {
    tableNames.value.push({
      id: null,
      name: '',
      type: 'varchar',
      notes: '',
      long: 255,
      edit: true,
      old: null,
      del: false,
    })
    window.scrollTo({
      top: document.body.scrollHeight,
      behavior: 'smooth' // 可选，用于平滑滚动
    });
    setTimeout(() => {
      window.scrollTo({
        top: document.body.scrollHeight,
        behavior: 'smooth' // 可选，用于平滑滚动
      });
    }, 233)
  };
  // 打开修改
  const openUpdateDialog = (row) => {
    //console.log(row)
    if (row.id != null) {
      if (row.edit) {
        if (row.old.name == row.name && row.old.type == row.type && row.old.notes == row.notes && row.old.long == row.long) {
          row.old = null
        }
      } else {
        row.old = JSON.parse(JSON.stringify(row))
      }
    }
    if (row.edit) {
      newDialogVisible.value = true
    }
    // 切换编辑模式
    row.edit = !row.edit;
  };

  const delDialogVisible = ref(false);
  const newDialogVisible = ref(false);
  // 打开删除确认
  const openDelDialog = (row) => {
    currentTable = {}
    //console.log(row)
    currentTable = row
    delDialogVisible.value = true
    row.edit = false
  }
  // 确认删除行
  const delRow = () => {
    currentTable.del = true
    let delindex = -1
    tableNames.value.forEach((item, index) => {
      if (currentTable == item && currentTable.id == null) {
        delindex = index
      }
    });
    if (delindex != -1) {
      tableNames.value.splice(delindex, 1); // 使用 splice 来删除元素
    }
    saveDialog()
  }

  // 撤回删除行
  const retrunDelDialog = (row) => {
    row.del = false
  }

  const updateList = ref([])
  const addList = ref([])
  const delList = ref([])

  // 保存修改
  const saveChanges = (row) => {
    // 这里实现保存逻辑，发送请求到服务器
    addList.value.forEach(item => {
      addUts(item)
    })
    delList.value.forEach(item => {
      delUts(item)
    })
    updateList.value.forEach(item => {
      updateUts(item)
    })
    Toast('操作完成！')
    tableNames.value = []
    setTimeout(() => {
      getTable()
    }, 555)

  }

  // 新增
  const addUts = (item) => {
    //console.log(item)
    let requestBody = {
      key: "addTable",
      CmdType: "sys",
      DBQueryData: [{
        key: "@dbName",
        value: localStorage.getItem('selectdb'),
        valueType: "string",
      }, {
        key: "@TBName",
        value: dbradio.value,
        valueType: "string",
      }, {
        key: "@name",
        value: item.name,
        valueType: "string",
      }, {
        key: "@type",
        value: item.type,
        valueType: "string",
      }, {
        key: "@long",
        value: item.long ? "(" + item.long + ")" : "",
        valueType: "string",
      }, {
        key: "@notes",
        value: item.notes,
        valueType: "string",
      },]
    }
    $http.post('DataHandle/CUD_InfoCommon', requestBody)
      .then(rs => {
        //console.log(rs)
        if (rs.data.isok) {

        } else {
          Toast(rs.data.message)
        }
      })
      .catch(error => {
        // 处理错误情况
        console.error(error);
      })
  }
  // 删除
  const delUts = (item) => {
    let requestBody = {
      key: "deleteTable",
      CmdType: "sys",
      DBQueryData: [{
        key: "@dbName",
        value: localStorage.getItem('selectdb'),
        valueType: "string",
      }, {
        key: "@TBName",
        value: dbradio.value,
        valueType: "string",
      }, {
        key: "@name",
        value: item.name,
        valueType: "string",
      }]
    }
    $http.post('DataHandle/CUD_InfoCommon', requestBody)
      .then(rs => {
        //console.log(rs)
        if (rs.data.isok) {

        } else {
          Toast(rs.data.message)
        }
      })
      .catch(error => {
        // 处理错误情况
        console.error(error);
      })
  }
  // 更新
  const updateUts = (item) => {
    let requestBody = {
      key: "updateTable",
      CmdType: "sys",
      DBQueryData: [{
        key: "@dbName",
        value: localStorage.getItem('selectdb'),
        valueType: "string",
      }, {
        key: "@TBName",
        value: dbradio.value,
        valueType: "string",
      }, {
        key: "@name",
        value: item.name,
        valueType: "string",
      }, {
        key: "@oldName",
        value: item.old.name,
        valueType: "string",
      }, {
        key: "@type",
        value: item.type,
        valueType: "string",
      }, {
        key: "@long",
        value: item.type == 'varchar' ? (item.long ? '(' + item.long + ')' : '(255)') : '',
        valueType: "string",
      }, {
        key: "@notes",
        value: item.notes,
        valueType: "string",
      },]
    }
    $http.post('DataHandle/CUD_InfoCommon', requestBody)
      .then(rs => {
        //console.log(rs)
        if (rs.data.isok) {

        } else {
          Toast(rs.data.message)
        }
      })
      .catch(error => {
        // 处理错误情况
        console.error(error);
      })

  }


</script>

<style scoped>
  .container {
    min-height: 85vh;
  }

  .fab-button {
    position: fixed;
    right: 16px;
  }




  /* PC端样式 */
  @media (min-width: 1024px) {
    .container {
      margin-top: 5px;
    }
  }
</style>
