<script lang="ts">
export default {
  name: 'dept'
};
</script>

<script setup lang="ts">
import { onMounted, reactive, ref, nextTick } from 'vue';
import { ElMessage, ElMessageBox, FormRules } from 'element-plus'
import Sortable from 'sortablejs';
import { useAppStore } from '@/store/modules/app';
import Page from '@/components/Pagination/page.vue'
import {
  getTreelist, addDict, updateDict, deleteById, changeDictOrder, getDictItemById, addDictionaryItem, updateDictionaryItem, deleteDictItemById, deleteDictItemByIds, changeItemOrder
} from '@/api/dict';
import Eldialog from '@/components/seccmsdialog/eldialog.vue';
const treeloading = ref(false);
const activeName = ref('00');
// 左侧树 - 数据
const treedata: any = ref([])
const treeRef = ref();
const treeId = ref('');
const defaultProps = { label: 'dictName' }
// 字典弹框
const title = ref('');
const dialogdict = ref(false);
const dictInfoRef = ref()
const dictInfo = ref({
  id: "",
  dictCode: "",
  dictName: "",
  dictType: "",
});
// 字典弹框规则
const rules = reactive<FormRules>({
  dictName: [{ required: true, message: "请输入字典名称", trigger: "blur" }, { validator: stringlength, trigger: 'blur' }],
  dictCode: [{ required: true, message: "请输入字典编码", trigger: "blur" }, { validator: stringlength1, trigger: 'blur' }]
});
//区域名称长度
function stringlength(rule: any, value: any, callback: any) {
  if (value.length > 100) {
    return callback(new Error('字符最大长度不超过100'))
  }
  callback()
}
function stringlength1(rule: any, value: any, callback: any) {
  if (value.length > 20) {
    return callback(new Error('字符最大长度不超过20'))
  }
  callback()
}
// 右侧查询
const querystr = ref({
  dictId: '',
  dictName: '',
  size: 10,
  current: 1
});
// 右侧表格
const tableData = ref([]) as any;
const multipleSelection: any = ref([]);
// const total = ref(0);
const tableloading = ref(false);
// 右侧新增/修改弹框弹框
const titleItem = ref('');
const dialogdictItem = ref(false);
const dictInfoRefItem = ref()
const dictInfoItem = ref({
  id: "",
  dictId: "",
  itemCode: "",
  dictName: "",
  parentCode: "",
  custom1: ""
});
// 字典弹框规则
const dictItemrules = reactive<FormRules>({
  dictName: [{ required: true, message: "请输入项名称", trigger: "blur" }, { validator: stringlength, trigger: 'blur' }],
  itemCode: [{ required: true, message: "请输入项编码", trigger: "blur" }, { validator: stringlength1, trigger: 'blur' }]
});
// 初始加载
onMounted(() => {
  getTree()
  rowDrop()
})

const vMove = {
  mounted(el: any) {
    el.onmousedown = function (e: any) {
      var init = e.clientX;
      var parent: any = document.getElementById("silderLeft");
      const initWidth: any = parent.offsetWidth;
      document.onmousemove = function (e) {
        var end = e.clientX;
        var newWidth = end - init + initWidth;
        parent.style.width = newWidth + "px";
      };
      document.onmouseup = function () {
        document.onmousemove = document.onmouseup = null;
      };
    };
  }
}
function rowDrop() {
  const tbody = document.querySelector('.draggable .el-table__body-wrapper tbody');
  Sortable.create(tbody, {
    draggable: ".draggable .el-table__row",
    onEnd(data: any) {
      const newIndex = data.newIndex;
      const oldIndex = data.oldIndex;
      if (tableData.value[newIndex].id == tableData.value[oldIndex].id) {
        return false;
      }
      const params = {
        fromID: tableData.value[newIndex].id,
        toID: tableData.value[oldIndex].id,
      };
      changeItemOrder(params).then(() => {
        init();
      });
    }
  });
}
// 查询左侧树
function getTree() {
  const params = {
    dictType: activeName.value
  }
  treeloading.value = true
  getTreelist(params).then((res) => {
    treedata.value = res.data
    treeloading.value = false
    if (treeId.value == "") {
      treeId.value = res.data[0].id;
    }
    nextTick(() => {
      treeRef.value?.setCurrentKey(treeId.value);
    });
    if (res.data.length == 0) treeId.value = ''
    init();
  })
    .catch((error) => {
      treeloading.value = false
    })
}
// 左侧树点击
function handleNodeClick(row: any) {
  treeId.value = row.id;
  init();
}
// 系统配置 / 用户配置 - 切换
function activeNameChange(name: any) {
  activeName.value = name.props.name
  getTree()
}

// 新增字典
function dictAdd() {
  title.value = "新增字典";
  dialogdict.value = true;
  const info = ref({
    id: "",
    dictCode: "",
    dictName: "",
    dictType: activeName.value,
  });
  dictInfo.value = info.value;
}
//修改字典
function dictEdit(data: any) {
  title.value = "修改字典";
  dictInfo.value = JSON.parse(JSON.stringify(data));
  dialogdict.value = true;
}
//删除字典
function dictDel(data: any) {
  ElMessageBox.confirm("确定删除该字典及该字典下的所有项吗？", "删除提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    let params = {
      id: data.id,
    };
    deleteById(params).then((res: any) => {
      if (res.code == 0) {
        getTree();
        ElMessage({
          message: "删除成功",
          type: "success",
        });
      }

    });
  });
}
// 字典保存
function dictSave(formEl: any) {
  formEl.validate((valid: any) => {
    if (valid) {
      if (!dictInfo.value.id) {
        const params = {
          dictCode: dictInfo.value.dictCode,
          dictName: dictInfo.value.dictName,
          dictType: dictInfo.value.dictType,
        };
        addDict(params).then((res: any) => {
          if (res.code == 0) {
            getTree();
            dialogdict.value = false;
            ElMessage({
              type: "success",
              message: "新增成功",
            });
          }

        })
      } else if (dictInfo.value.id) {
        const params = {
          dictCode: dictInfo.value.dictCode,
          dictName: dictInfo.value.dictName,
          dictType: dictInfo.value.dictType,
          id: dictInfo.value.id,
        };
        updateDict(params).then((res: any) => {
          if (res.code == 0) {
            getTree();
            dialogdict.value = false;
            ElMessage({
              type: "success",
              message: "修改成功",
            });
          }

        });
      } else {
        return false;
      }
    }
  })
}
// 左侧排序
function treenodeDrop(before: any, after: any) {
  const params = {
    fromID: before.data.id,
    toID: after.data.id,
  };
  changeDictOrder(params).then(() => {
    getTree();

  });
}
const allowDrop = (draggingNode: any, dropNode: any, type: any) => {
  // 不能拖拽到级别里面
  if (type === 'inner' || Number(dropNode.data.pid) === 0) return
  if (draggingNode.nextSibling === undefined) {
    return type === 'prev'
  } else if (dropNode.nextSibling === undefined) {
    return type === 'next'
  } else if (draggingNode.nextSibling.id !== dropNode.id) {
    return type === 'prev'
  } else {
    return type === 'next'
  }
}
// 关闭字典弹框
function dictClose() {
  dictInfoRef.value.resetFields();
  dialogdict.value = false;
}
// 查询字典项
function init() {
  tableloading.value = true;
  querystr.value.dictId = treeId.value;
  getDictItemById(querystr.value).then((result: any) => {
    if (result.data.records == null) {
      tableData.value = []
      total.value = 0;
      tableloading.value = false;
      return
    }
    tableData.value = result.data.records;
    total.value = result.data.total;
    querystr.value.size = result.data.size;
    querystr.value.current = result.data.current
    tableloading.value = false;
  }).catch((err: any) => {
    tableloading.value = false;
  });
}
// 新增字典项
function addClick() {
  titleItem.value = "新增项";
  dialogdictItem.value = true;
  const info = ref({
    id: "",
    dictId: querystr.value.dictId,
    itemCode: "",
    dictName: "",
    parentCode: "",
    custom1: ""
  });
  dictInfoItem.value = info.value;
}
// 修改字典项
function editClick(data: any) {
  titleItem.value = "修改项";
  dictInfoItem.value = JSON.parse(JSON.stringify(data));
  dialogdictItem.value = true;
}
// 删除字典项
function delClick(data: any) {
  ElMessageBox.confirm("确定删除此项吗?", "删除提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    let params = {
      id: data.id,
    };
    deleteDictItemById(params).then((res: any) => {
      if (res.code == '0') {
        init();
        ElMessage({
          message: "删除成功",
          type: "success",
        });
      }

    });
  });
}
// 多选删除字典项
function delsClick() {
  ElMessageBox.confirm("确定删除已选择的项吗？", "删除提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    let id = [] as any[];
    multipleSelection.value.forEach((item: any) => {
      id.push(item.id)
    })
    let params = {
      id: id.join(','),
    };
    deleteDictItemByIds(params).then((res: any) => {
      if (res.code == '0') {
        init();
        ElMessage({
          message: "删除成功",
          type: "success",
        });
      }

    });
  });
}
// 关闭字典项弹框
function dictItemClose() {
  dictInfoRefItem.value.resetFields();
  dialogdictItem.value = false;
}
// 字典项保存
function dictItemSave(formEl: any) {
  formEl.validate((valid: any) => {
    if (valid) {
      if (!dictInfoItem.value.id) {
        const params = {
          dictId: dictInfoItem.value.dictId,
          itemCode: dictInfoItem.value.itemCode,
          dictName: dictInfoItem.value.dictName,
          parentCode: dictInfoItem.value.parentCode,
          custom1: dictInfoItem.value.custom1
        };
        addDictionaryItem(params).then((res: any) => {
          if (res.code == '0') {
            init();
            dialogdictItem.value = false;
            ElMessage({
              type: "success",
              message: "新增字典项成功",
            });
          }

        })
      } else if (dictInfoItem.value.id) {
        const params = {
          dictId: dictInfoItem.value.dictId,
          itemCode: dictInfoItem.value.itemCode,
          dictName: dictInfoItem.value.dictName,
          parentCode: dictInfoItem.value.parentCode,
          custom1: dictInfoItem.value.custom1,
          id: dictInfoItem.value.id,
        };
        updateDictionaryItem(params).then((res: any) => {
          if (res.code == '0') {
            init();
            dialogdictItem.value = false;
            ElMessage({
              type: "success",
              message: "修改字典项成功",
            });
          }

        });
      } else {
        return false;
      }
    }
  })
}
// 表格多选
function handleSelectionChange(val: any) {
  multipleSelection.value = val;
}
//表格多选样式
const tableRowClassName = ({
  row,
  rowIndex,
}: {
  row: any
  rowIndex: number
}) => {
  if (rowIndex % 2 === 0) {
    return 'warning-row'
  } else if (rowIndex % 2 === 1) {
    return 'success-row'
  }
  return ''
}

//分页
const total = ref()

</script>
<template>
  <div class="faulttemplate-box">
    <aside id="silderLeft">
      <el-tabs :class="useAppStore().size === 'default' ? 'silderLeft-large' : 'silderLeft-default'" v-model="activeName"
        class="demo-tabs" @tab-click="activeNameChange">
        <el-tab-pane label="系统配置" name="00"></el-tab-pane>
        <el-tab-pane label="用户配置" name="01"></el-tab-pane>
      </el-tabs>
      <div class="menu-box">
        <el-button  class="searchButton"
          style=" color: #009bff; border: 1px solid #009bff;width:100%;margin-bottom:10px;background-color: #123958;"
          @click="dictAdd">
          新增字典</el-button>
        <el-scrollbar height="calc(77vh)">
          <el-tree v-loading="treeloading" ref="treeRef"
            :class="useAppStore().size === 'default' ? 'silderLeft-large' : 'silderLeft-default'" node-key="id"
            :allow-drop="allowDrop" :data="treedata" draggable :highlight-current="true" :props="defaultProps"
            @node-click="handleNodeClick" @node-drop="treenodeDrop" style="overflow: auto;">
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span class="custom-tree-node-img">
                  <img src="@/assets/images/linefeed.png" alt="">
                  <span>{{ node.label }}</span>
                </span>
                <span>
                  <el-icon class="treeediticon" title="修改" @click="() => dictEdit(data)">
                    <EditPen />
                  </el-icon>
                  <el-icon class="treedelicon" title="删除" @click="() => dictDel(data)">
                    <Delete />
                  </el-icon>
                </span>
              </span>
            </template>
          </el-tree>
        </el-scrollbar>
      </div>
      <div class="moveBtn" v-move>
        <div class="moveBtn-line"></div>
      </div>
    </aside>
    <section class="silderRight">
      <el-row>
        <el-col :span="24" class="top-nav">
          <div style="margin-bottom:10px">
            <el-input v-model="querystr.dictName" placeholder="请输入项名称" clearable style="width: 200px;margin-right: 10px;"
              @clear="init" @keyup.enter="init" />
            <el-button  class="searchButton" type="primary" @click="init">搜索</el-button>
          </div>
          <div class="left-nav">
            <el-button  class="searchButton" type="primary" @click="addClick()"> 新增</el-button>
            <el-button   class="searchButton" :type="multipleSelection.length > 0 ? 'primary' : ''" :disabled="multipleSelection.length <= 0"
              @click="delsClick">
              删除</el-button>
          </div>
        </el-col>
      </el-row>
      <div class="draggable">
        <el-table v-loading="tableloading" :data="tableData" row-key="id" style="width: 100%;margin-bottom: 20px;height: calc(77vh);
                overflow: auto;" border @selection-change="handleSelectionChange" default-expand-all
          :row-class-name="tableRowClassName"
          :header-cell-style="{ background: '#002b6a', color: '#B5D7FF', height: '50px'}">
          <el-table-column type="selection" width="30" align="center" />
          <el-table-column prop="orderNo" label="序号" width="50">
            <template #default="scope">
              <span class="custom-tree-node-img">
                <img src="@/assets/images/linefeed.png" alt="">
                {{ scope.row.orderNo }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="itemCode" label="项编码" width="160"></el-table-column>
          <el-table-column prop="dictName" label="项名称"></el-table-column>
          <el-table-column prop="parentCode" label="父项编码" ></el-table-column>
          <el-table-column prop="custom1" label="备注"></el-table-column>
          <el-table-column fixed="right" label="操作" width="110">
            <template #default="scope">
              <span
                style="display: flex;display: -webkit-flex; justify-content: space-around; -webkit-justify-content: space-around;">
                <img src="@/assets/newimg/ht_xg.png" alt="" itle="修改" style="cursor: pointer;"
                  @click="editClick(scope.row)">
                <img src="@/assets/newimg/ht_sc.png" alt="" title="删除" style="cursor: pointer;"
                  @click="delClick(scope.row)">
              </span>
            </template>
          </el-table-column>
        </el-table>
        <Page :total="total" v-model:size="querystr.size" v-model:current="querystr.current" @pagination="init()"></Page>
      </div>
    </section>

    <!-- 子项 弹框-->
    <Eldialog v-if="dialogdictItem" :title="title" :zIndex="2000" :width="'620px'" :height="'600px'"
      @before-close="dictItemClose">
      <template v-slot:PopFrameContent>
        <el-form ref="dictInfoRefItem" :model="dictInfoItem" label-width="80px" style="margin-top:15px"
          :rules="dictItemrules">
          <el-form-item label="项编码" prop="itemCode">
            <el-input v-model="dictInfoItem.itemCode" style="width:95%" placeholder="请输入项编码"></el-input>
          </el-form-item>
          <el-form-item label="项名称" prop="dictName">
            <el-input v-model="dictInfoItem.dictName" style="width:95%" placeholder="请输入项名称"></el-input>
          </el-form-item>
          <el-form-item label="父项编码" prop="parentCode">
            <el-input v-model="dictInfoItem.parentCode" style="width:95%" placeholder="请输入父项编码"></el-input>
          </el-form-item>
          <p style="color:#f56c6c;font-size: 12px;width: 70%;margin: auto; margin-top: -15px; padding: 5px 0px;">
            注：如果添加项为子项，则需输入父项编码</p>
          <el-form-item label="备注">
            <el-input v-model="dictInfoItem.custom1" rows="5" type="textarea" :autosize="{ minRows: 2, maxRows: 8 }"
              style="width:95%" placeholder="请输入备注"></el-input>
          </el-form-item>
        </el-form>
        <span class="dialog-footer"
          style="display: flex; display: -webkit-flex; justify-content: center; -webkit-justify-content: center;margin: 10px 0px;">
          <div class="details-button" @click="dictItemClose">取消</div>
          <div class="details-button" @click="dictItemSave(dictInfoRefItem)">确定</div>
        </span>
      </template>
    </Eldialog>
    <!-- <el-dialog v-model="dialogdictItem" :before-close="dictItemClose" :title="titleItem" draggable width="620px">
     
    </el-dialog> -->
    <!-- 字典弹框-->
    <Eldialog v-if="dialogdict" :title="title" :zIndex="2000" :width="'620px'" :height="'600px'"
      @before-close="dictClose">
      <template v-slot:PopFrameContent>
        <el-form ref="dictInfoRef" :model="dictInfo" label-width="90px" style="margin-top:15px" :rules="rules">
          <el-form-item label="字典类型">
            <el-input :value="dictInfo.dictType == '00' ? '系统配置' : '用户配置'" style="width:95%" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="字典编码" prop="dictCode">
            <el-input v-model="dictInfo.dictCode" style="width:95%" placeholder="请输入字典编码"></el-input>
          </el-form-item>
          <el-form-item label="字典名称" prop="dictName">
            <el-input v-model="dictInfo.dictName" style="width:95%" placeholder="请输入字典名称"></el-input>
          </el-form-item>
        </el-form>
        <span class="dialog-footer"
          style="display: flex;display: -webkit-flex; justify-content: center;-webkit-justify-content: center;margin: 10px 0px;">

          <div class="details-button" @click="dictClose">取消</div>
          <div class="details-button" @click="dictSave(dictInfoRef)">确定</div>
        </span>
      </template>
    </Eldialog>
    <!-- <el-dialog v-model="dialogdict" :before-close="dictClose" :title="title" draggable width="620px">
      
    </el-dialog> -->
  </div>
</template>
<style lang="scss" scoped>
.silderLeft-default {
  :deep(.custom-tree-node, .treedelicon, .treeediticon) {
    font-size: 16px !important;
  }

  :deep(.custom-tree-large, .treedelicon, .treeediticon) {
    font-size: 14px !important;
  }

  :deep(.el-tabs__item) {
    font-size: 16px !important;
  }
}

.faulttemplate-box {
  height: 100%;
  display: flex;
  background-color: #f2f4f900;
  display: -webkit-flex;
  padding: 17px 15px 8px 15px;
}

#silderLeft {
  width: 300px;
  padding: 10px;
  box-sizing: border-box;
  background: #ffffff00;
  border-radius: 3px;
  position: relative;
  background: url(@/assets/navigation/ty_260x988.png);
  background-size: 100% 100%;

  &:hover {
    .moveBtn {
      opacity: 1;
    }
  }
}

/* 拖动条 */
.moveBtn {
  height: 100%;
  width: 15px;
  padding: 0 6px;
  opacity: 0;
  position: absolute;
  right: -15px;
  top: 0;
}

.moveBtn-line {
  width: 100%;
  height: 100%;
  cursor: col-resize;
  user-select: none;
  background-color: #60bfff;
}

.silderRight {
  flex: 1;
  width: 100%;
  height: calc(100vh - 160px);
  overflow: auto;
  background-color: rgba(255, 255, 255, 0);
  border-radius: 3px;
  padding: 15px;
  padding-bottom: 0px;
  box-sizing: border-box;
  margin-left: 15px;
  background: url(@/assets/newimg/cjrw_1890.png);
background-size: 100% 100%;

}

.custom-tree-node {
  flex: 1;
  display: flex;
  display: -webkit-flex;
  align-items: center;
  -webkit-align-items: center;
  justify-content: space-between;
  -webkit-justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.custom-tree-node-img {
  img {
    display: inline-block;
    margin-right: 5px;
    vertical-align: baseline;
    user-select: none;
    -webkit-user-drag: none;
  }
}
.faulttemplate-box {
  .is-current .treeediticon {
    color: #009bff !important;
  }

  .is-current .treedelicon {
    color: #ffffff !important;
  }

  .el-tree-node__content:hover .treeediticon {
    color: #009bff;
  }

  .el-tree-node__content:hover .treedelicon {
    color: #009bff;
  }
}

.treeediticon,
.treedelicon {
  color: #009bff;
  margin: 0 5px;
  font-size: 16px;
}

.top-nav {
  display: flex;
  display: -webkit-flex;
  justify-content: space-between;
  -webkit-justify-content: space-between;
}

.faulttemplate-box {
  display: flex;
  display: -webkit-flex;
  background-color: #f2f4f900;
}


:deep(.el-tree-node__content) {
  width: 100%;
  height: 40px;
  line-height: 40px;
}

.faulttemplate-box {
  .is-current .treeediticon {
    color: #009bff !important;
  }

  .is-current .treedelicon {
    color: #009bff !important;
  }

  .el-tree-node__content:hover .treeediticon {
    color: #009bff;
  }

  .el-tree-node__content:hover .treedelicon {
    color: #009bff;
  }
}

.treeediticon,
.treedelicon {
  color: #009bff;
  margin: 0 5px;
  font-size: 16px;
}

.top-nav {
  display: flex;
  display: -webkit-flex;
  justify-content: space-between;
  -webkit-justify-content: space-between;
}

:deep(.el-select .el-input) {
  width: 80px !important;
}

:deep(.el-table:not(.el-table--border) .el-table__cell) {
  border: none;
  color: #fff !important;
}

:deep(.el-tree) {
  background-color: #ffffff00 !important;
  --el-tree-node-hover-bg-color: #0099ff09;
}

:deep(.el-input) {
  --el-input-bg-color: #ffffff00 !important;
}
</style>