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

   <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 v-model="scope.row.data" placeholder="输入子增长的起始值和位数" v-if="scope.row.rule===6"></el-input>
           </div>
            <span v-else>{{ scope.row.data }}</span>
          </template>
        </el-table-column>

        <el-table-column label="是否自增">
          <template slot-scope="scope">
             <el-checkbox v-model="scope.row.isAutoIncrement" v-if="scope.row.rule==6" :true-label="1" :false-label="0"></el-checkbox>
          </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

  >
       <el-table
        :data="sortedTableData"
        style="width: 100%"
      >
        <el-table-column label="序号" type="index" width="50"></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">
              <span>{{ scope.row.data }}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否自增">
          <template slot-scope="scope">
             <el-checkbox v-model="scope.row.isAutoIncrement" v-if="scope.row.rule==6" :true-label="1" :false-label="0"></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
            <template slot-scope="scope">
              <el-button
                type="text"
                icon="el-icon-arrow-up"
                @click="handleSortUp(scope.$index)"
                style="margin-right: 5px;"
              ></el-button>
              <el-button
                type="text"
                icon="el-icon-arrow-down"
                @click="handleSortDown(scope.$index)"
              ></el-button>
            </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>
    
  </el-dialog>
</template>

<script>
import {getTrialNumberRule,save,update,remove,sort } from "@/api/ruleManage/codeRule.js";
import { getDictionary } from "@/api/system/dict";
export default {
  name: 'FileRuleDialog',
  
  data() {
    return {
      projectId: '',

      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状态

    }
  },

  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.sortDialogVisible = true; // 显示排序弹窗
    },
  handleSortUp(index) {
    if (index > 0) { // 确保不是第一行
      const temp = this.sortedTableData.splice(index, 1)[0]; // 移除当前行
      this.sortedTableData.splice(index - 1, 0, temp); // 在上一行插入
   
    } else {
      this.$message.warning('已经是第一行，无法上移');
    }
  },

  handleSortDown(index) {
    if (index < this.sortedTableData.length - 1) { // 确保不是最后一行
      const temp = this.sortedTableData.splice(index, 1)[0]; // 移除当前行
      this.sortedTableData.splice(index + 1, 0, temp); // 在下一行插入
    
    } else {
      this.$message.warning('已经是最后一行，无法下移');
    }
  },
  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);
            this.sortDialogVisible = false; // 关闭排序弹窗
            
          }
        }).catch(() => {
          this.$message.error('操作失败');
        }).finally(() => {
          this.sortLoad = 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'];
                    }else{
                        this.tableData = [];
                    }
                })
    },


    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;
    }
        row.loading = true;
        const apiMethod = row.id ? update : save;
        const params = {
          ...row,
          type: this.activeName,
          projectId: this.projectId,
          contractId: 0
        };

        apiMethod(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(() => {
          row.loading = false;
          row.isEdit = 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;
  }
}
</style>