<template>
  <el-dialog
    title="编号配置" 
    :visible.sync="dialogVisible"
    width="70%"
    append-to-body
    :close-on-click-modal="false"


  >

   <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
    <el-tab-pane  v-for="item in activeOptions"  :label="item.label" :name="item.value">
    <div class="file-rule-container">
         
     <div class="header-box">
       <div class="preview-box">
        <span>生成预览</span>
        <el-input v-model="dataNumber" placeholder="预览编号" style="width: 300px; margin-left: 10px;" disabled size="small"></el-input>
      </div>
        <div class="header-tools">
            
            <el-button type="text" icon="el-icon-plus" @click="addRow">新增</el-button>
            <el-button type="text" icon="el-icon-sort" @click="sortData">排序</el-button>
            <el-button type="text" icon="el-icon-delete" @click="delBatchData" style="color: #F56C6C;" :loading="delLoad">删除</el-button>
        </div>
     </div>
      
      <el-table
 
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        ref="multipleTable"
        @selection-change="handleSelectionChange"
      >
        <el-table-column label="序号" type="index" width="50"></el-table-column>
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column label="规则">
          <template slot-scope="scope">
            <el-select 
              v-if="scope.row.isEdit"
              v-model="scope.row.rule" 
              @change="handleNumberChange($event,scope.row)"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="item in numberOptions"
                :key="item.dictKey"
                :label="item.dictValue"
                :value="item.dictKey"
              >
              </el-option>
            </el-select>
             <span v-else>{{ getDictValueByRule(scope.row.rule) }}</span>
           
          </template>
        </el-table-column>

        <el-table-column label="数据填充">
          <template slot-scope="scope">
           <div  v-if="scope.row.isEdit">
             <el-input v-model="scope.row.data" placeholder="*输入生成编号时包含的固定字符" v-if="scope.row.rule===1"></el-input>
            <el-input v-model="scope.row.data" placeholder="*自动获取当前合同段编号" v-if="scope.row.rule===2" disabled></el-input>
            <el-input v-model="scope.row.data" placeholder="*自动获取各试验参数掩码" v-if="scope.row.rule===3" disabled></el-input>
            <el-input v-model="scope.row.data" placeholder="*自动获取当前年份" v-if="scope.row.rule===4" disabled></el-input>
             <el-input v-model="scope.row.data" placeholder="*自动获取当前月份" v-if="scope.row.rule===5" disabled></el-input>
             <el-input
               ref="inputField"
              v-bind:class="{ 'input-error': scope.row.rule === 6 && !scope.row.data }"
              v-model="scope.row.data"
              v-if="scope.row.rule === 6"
              @input="scope.row.data = scope.row.data.replace(/[^0-9]/g, '')"></el-input>

             
           </div>
            <!-- <span v-else>{{ scope.row.data }}</span> -->
             <div v-else>
               
                    <span>{{ scope.row.data }}</span>
             </div>
          </template>
        </el-table-column>

        <el-table-column label="是否自增" >
          <template slot-scope="scope" v-if="scope.row.rule==6">
             <el-checkbox v-model="scope.row.isAutoIncrement" v-if="scope.row.rule==6&&scope.row.isEdit" :true-label="1" :false-label="0" ></el-checkbox >
                  <span v-else>{{scope.row.isAutoIncrement===1?'是':'否'}}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="handleEdit(scope.$index, scope.row)"
              v-if="!scope.row.isEdit"
            >
              编辑
            </el-button>
            <el-button
              type="text"
              @click="handleSave(scope.$index, scope.row)"
              :loading="scope.row.loading"
              v-else
            >
              保存
            </el-button>
            <el-button
              type="text"
              @click="handleDelete(scope.$index, scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    </el-tab-pane>
    
  </el-tabs>
   
<template>
  <!-- 省略其他代码 -->
  
  <el-dialog
    title="排序"
    :visible.sync="sortDialogVisible"
    width="50%"
    append-to-body
    @close="handleSortDialogClose"

  >
       <el-table
        :data="sortedTableData"
        style="width: 100%"
        :key="sortedTableDataKey"
        ref="sortTable"
          row-key="id"
      >
        <el-table-column label="序号" type="index" width="50"></el-table-column>
        <!-- 新增的快速排序列 -->
        <el-table-column label="快速排序" width="120">
            <template slot-scope="scope">
                <el-input-number
                style="width: 100px;"
                    v-model="scope.row.sortOrder"
                    :min="1"
                    :max="sortedTableData.length"
                    size="mini"
                    :controls="false"
                    @change="handleQuickSort(scope.row, scope.$index)"
                ></el-input-number>
            </template>
        </el-table-column>
        <el-table-column label="规则">
          <template slot-scope="scope">
             <span >{{ getDictValueByRule(scope.row.rule) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="数据填充">
          <template  slot-scope="scope">
             <div>
          
                    <span >{{ scope.row.data }}</span>
             </div>
          </template>
        </el-table-column>
        <el-table-column label="是否自增">
          <template slot-scope="scope"  v-if="scope.row.rule==6">
            <span >{{scope.row.isAutoIncrement===1?'是':'否'}}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
            <template slot-scope="scope">
                  <div style="display: flex; align-items: center;">
                      <!-- 拖拽手柄 -->
                      <i class="el-icon-rank drag-handle" 
                        style="cursor: move; margin-right: 10px; color: #409EFF;"></i>
                      
                      <!-- 上下移动按钮 -->
                      <el-button
                        type="text"
                        icon="el-icon-top"
                        @click="handleSortUp(scope.$index)"
                        style="margin-right: 5px;"
                      ></el-button>
                      <el-button
                        type="text"
                        icon="el-icon-bottom"
                        @click="handleSortDown(scope.$index)"
                      ></el-button>
                    </div>
            </template>
          </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
          <el-button @click="sortDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="sortSave" :loading="sortLoad">确 定</el-button>
        </div>
  </el-dialog>
</template>
     <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="saveCodeSet" :loading="saveCodeLoad">确 定</el-button>
  </span>
  </el-dialog>
</template>

<script>
import {getTrialNumberRule,save,update,remove,sort,submitList } from "@/api/ruleManage/codeRule.js";
import { getDictionary } from "@/api/system/dict";
import Sortable from 'sortablejs';
export default {
  name: 'FileRuleDialog',
  
  data() {
    return {
      projectId: '',
      saveCodeLoad: false,
      dialogVisible: false,
      loading: false,
      tableData: [],
      tableLoading: false,

      numberOptions: [
       
      ],
      dataNumber: '',
      activeName:'1',
      activeOptions: [
        { label: '材料编号', value: '1' },
        { label: '样品编号', value: '2' },
        { label: '委托单编号', value: '3' },
        { label: '记录表编号', value: '4' },
        { label: '报告表编号', value: '5' },
      ],
      multipleSelection:[],
      delLoad: false,
      sortDialogVisible: false, // 控制排序弹窗的显示与隐藏
      sortedTableData: [], // 排序弹窗的表格数据，为tableData的深拷贝
      sortLoad: false, // 排序保存按钮的loading状态
      sortedTableDataKey: 0, // 控制排序弹窗表格的key，用于强制更新
      sortable: null,
      isDragging: false


    }
  },
  watch: {
    // 监听对话框显示状态
    sortDialogVisible(val) {
      if (val) {
        this.$nextTick(() => {
          this.initSortable();
        });
      } else {
        this.destroySortable();
      }
    }
  },
  methods: {


    show(pid) {
      this.dialogVisible = true
      this.projectId = pid
      this.getTableData()
      this.getNumberOptions()

    },

    handleClick(tab, event) {
      this.dataNumber=''
      this.getTableData()
    },
    addRow() {
      this.tableData.push({
        isEdit: true,
      })
    },
    sortData() {
      this.sortedTableData = JSON.parse(JSON.stringify(this.tableData)); // 深拷贝tableData
     this.sortedTableData.forEach((item, index) => {
                this.$set(item, 'sortOrder', index + 1);
            });
      this.sortDialogVisible = true; // 显示排序弹窗
     this.$nextTick(()=>{
       this.initSortable(); // 初始化拖拽排序
     }
    )

    },
    handleSortDialogClose(){
      this.destroySortable();
    },

    
    // 上移
    handleSortUp(index) {
        if (index <= 0) return;
        
        const newData = [...this.sortedTableData];
        [newData[index - 1], newData[index]] = [newData[index], newData[index - 1]];
        
        // 更新所有行的sortOrder
        newData.forEach((item, i) => {
            item.sortOrder = i + 1;
        });
        
        this.sortedTableData = newData;
    },
    
// 快速排序处理函数
    
    // 快速排序处理
    handleQuickSort(row, index) {
        const targetIndex = row.sortOrder - 1;
        if (targetIndex === index) return;
        
        const newData = [...this.sortedTableData]; // 创建新数组
        const [movedItem] = newData.splice(index, 1);
        newData.splice(targetIndex, 0, movedItem);
        
        // 更新所有行的sortOrder
        newData.forEach((item, i) => {
            item.sortOrder = i + 1;
        });
        
        this.sortedTableData = newData; // 替换整个数组触发响应式更新
        console.log( this.sortedTableData,' this.sortedTableData');
        this.sortedTableDataKey++; // 强制更新排序弹窗的表格
          this.$nextTick(()=>{
            this.initSortable(); // 初始化拖拽排序
          }
          )
        
    },
    // 下移
    handleSortDown(index) {
        if (index >= this.sortedTableData.length - 1) return;
        
        const newData = [...this.sortedTableData];
        [newData[index], newData[index + 1]] = [newData[index + 1], newData[index]];
        
        // 更新所有行的sortOrder
        newData.forEach((item, i) => {
            item.sortOrder = i + 1;
        });
        
        this.sortedTableData = newData;
           this.$nextTick(()=>{
            this.initSortable(); // 初始化拖拽排序
          }
          )
    },
        // 初始化拖拽排序
       // 初始化拖拽排序
    initSortable() {
      this.destroySortable(); // 先销毁旧的实例
      
      const table = this.$refs.sortTable.$el.querySelector('.el-table__body-wrapper tbody');
      if (!table) return;
      
      this.sortable = new Sortable(table, {
        animation: 150,
        handle: '.drag-handle',
        ghostClass: 'sortable-ghost',
        onStart: () => {
          this.isDragging = true;
        },
        onEnd: ({ newIndex, oldIndex }) => {
            if (newIndex === oldIndex) return;
            
            // 更安全的移动方式
            const newArray = [...this.sortedTableData]; // 创建副本
            const [movedItem] = newArray.splice(oldIndex, 1);
            newArray.splice(newIndex, 0, movedItem);
            
            // 一次性更新数组
            this.sortedTableData = newArray;
            
            // 更新序号
            this.updateSortOrders();

        
          },
      });
    },
        // 安全销毁Sortable实例
    destroySortable() {
      if (this.sortable) {
        this.sortable.destroy();
        this.sortable = null;
      }
    },
       // 更新所有行的排序序号
    updateSortOrders() {
      const newData = this.sortedTableData.map((item, index) => {
      return {
        ...item,
        sortOrder: index + 1
      };
    });
    this.sortedTableData = newData;
       // 重新初始化拖拽
          this.$nextTick(() => this.initSortable());
    },
  sortSave(){
    this.sortLoad = true;
    let params=this.sortedTableData
       sort(params).then((res) => {
          if (res.data.code === 200) {
            this.dataNumber = res.data.data;
            this.$message.success(res.data.msg);
            this.getTableData();
          } else {
            this.dataNumber = '';
            this.$message.error(res.data.msg);
           
            
          }
        }).catch(() => {
          this.$message.error('操作失败');
        }).finally(() => {
          this.sortLoad = false;
           this.sortDialogVisible = false; // 关闭排序弹窗
        });

  },

    getNumberOptions(){
       getDictionary({
        code:'trial_number_rule',
      }).then((res) => {
       
        this.numberOptions = res.data.data;
        this.numberOptions.forEach(item=>{
         item.dictKey=Number(item.dictKey)

        })
      });
    },
    getTableData() 
    {
      this.tableLoading = true;
                getTrialNumberRule({
                   projectId:this.projectId,
                   contractId:0,
                   type:this.activeName,
             
                   pageSize:20
                }).then(res => {
                    this.tableLoading = false;
                    if (res.data.code == 200) {
                       
                        this.tableData = res.data.data['list'];
                        this.total = res.data.data['total'];
                        this.dataNumber=res.data.data['trialNumber']
                    }else{
                        this.tableData = [];
                         this.dataNumber='';
                    }
                })
    },


    refreshData() {
      this.loading = true
      // TODO: 调用接口刷新数据
      setTimeout(() => {
        this.loading = false 
      }, 500)
    },
    delBatchData(){
      if(this.multipleSelection.length===0){
        this.$message.warning('请选择要删除的规则！')
        return;
      }
     let ids = this.multipleSelection.map(item => item.id).join(',');

      this.$confirm('删除后，数据将无法恢复，是否确认删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.delLoad = true;
          return remove({ids: ids});
        }).then((res) => {
          if (res.data.code === 200) {
            this.$message.success(res.data.msg);
            this.dataNumber = res.data.data;
            this.getTableData();
          } else {
            this.$message.error(res.data.msg);
          }
        }).catch(() => {
          this.$message.info('已取消删除');
        }).finally(() => {
          this.delLoad = false;
        });
    },

    handleEdit(index, row) {
      this.$set(row, 'isEdit', true)
    },

   handleSave(index, row) {
    if(!row.rule) {
      this.$message.warning('请选择规则！')
      return;
    }
    if(row.rule===6&&!row.data){
      this.$message.warning('请输入数据填充！')
      return;
    }
     row.isEdit = false;
    },
    saveCodeSet(){
        if (this.tableData.length === 0) {
          this.$message.warning('请先填写数据！')
          return;
        }

        for (let [index, row] of this.tableData.entries()) {
            row.projectId = this.projectId;
            row.type = this.activeName;

            // 检查 row.rule 是否有值
            if (!row.rule) {
              // 显示警告信息
              this.$message.warning('请选择规则！');
              return
            } else if (row.rule === 6 && !row.data) {
              // 记录错误行的索引
          
              this.$message.warning('请输入数据填充！');
              return;
            }
          }
        
                  
  
      
          this.saveCodeLoad = true;
                  submitList(this.tableData).then((res) => {
                      if (res.data.code === 200) {
                        this.dataNumber = res.data.data;
                        this.$message.success(res.data.msg);
                        this.getTableData();
                      } else {
                        this.dataNumber = '';
                        this.$message.error(res.data.msg);
                      }
                    }).catch(() => {
                      // this.$message.error('操作失败');
                    }).finally(() => {
                            this.saveCodeLoad = false;
                    });
    },
    handleDelete(index, row) {
      if(!row.id) {
        this.tableData.splice(index, 1)
        return
      }
      this.$confirm('确认删除该规则?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        remove({ ids: row.id }).then((res) => {
          if (res.data.code === 200) {
            this.dataNumber = res.data.data;
            this.$message.success(res.data.msg);
            this.getTableData();
          } else {
            this.$message.error(res.data.msg);
          }
        })
        // this.tableData.splice(index, 1)
      })
    },

    handleNumberChange(data,row) {
      this.numberOptions.forEach(item => {
        if (item.dictKey === data) {
          row.ruleName = item.dictValue
        }
      })
    },
    getDictValueByRule(ruleKey) {
      const item = this.numberOptions.find(item => item.dictKey == ruleKey);
      return item ? item.dictValue : '未知';
    },
    handleSelectionChange(val) {
        this.multipleSelection = val;
    },



  
  }
}
</script>

<style lang="scss" scoped>
.file-rule-container {
  .header-box{
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-bottom: 20px;
     margin-right: 10px;
  }
  .header-tools {
    // display: flex;
    
    text-align: right;
  }

  .node-tree {
    margin-top: 10px;
    max-height: 200px;
    overflow-y: auto;
    border: 1px solid #EBEEF5;
    padding: 10px;
  }
}
.input-error {
  border-color: red;
}
/* 拖拽时的样式效果 */
.sortable-ghost {
  opacity: 0.5;
  background: #c8ebfb;
}

/* 拖拽手柄样式 */
.drag-handle {
  cursor: move;
  transition: color 0.2s;
}
.drag-handle:hover {
  color: #409EFF;
}
</style>
<style>
.input-error{
  .el-input__inner{
    border-color: red;
  }
}
</style>
