<template>
  <div>
    <el-card :body-style="cardBodyStyle">
      <el-form :inline="true">
        <el-form-item label="项目名称" style="margin-bottom: 5px;" prop="name">
          <el-input v-model="query.name" placeholder="请输入项目名称"
                    clearable></el-input>
        </el-form-item>
        <el-form-item label="编码" style="margin-bottom: 5px;" prop="bm">
          <el-input v-model="query.bm" placeholder="请输入编码"
                    clearable></el-input>
        </el-form-item>
      </el-form>
    </el-card>
    <ButtonBar area="top" @search="handleSearch" @add="handleAdd" @remove="handleRemoveBatch"></ButtonBar>
    <el-card :body-style="cardBodyStyle">
      <el-table :data="tableData"  border highlight-current-row @selection-change="handleSelectionChange" height="300" row-key="id"
                :default-expand-all="false">
        <el-table-column type="selection" fixed></el-table-column>
        <el-table-column v-if="true" prop="id" label="ID" align="center" width="100" type=""></el-table-column>
        <el-table-column v-if="true" prop="name" label="项目名称" width="200"
                         header-align="left" align="left"
                         show-overflow-tooltip tree-column="true">
        </el-table-column>
        <el-table-column v-if="true" prop="ziduan" label="项目简称" width="200"
                         header-align="center" align="center"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="remark" label="数据类型" width="200"
                         header-align="center" align="center"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="bm" label="编码" width="200"
                         header-align="center" align="center"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="sortindex" label="排序" width="200"
                         header-align="center" align="center"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="操作" header-align="center" align="center" width="200px">
          <template #default="scope">
            <el-button plain type="warning" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button plain type="danger" @click="handleDelete(scope.row )">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-card :body-style="cardBodyStyle">
      <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="pageSizes"
                     :total="totalRows" background="background" layout="total, sizes, prev, pager, next, jumper"
                     @size-change="handleSizeChange" @current-change="handleCurrentChange">
      </el-pagination>
    </el-card>

    <el-dialog :close-on-click-modal="false" draggable title="新增" v-model="dialogVisible" width="1210px"
                 top="5vh" @open="openDialog">
      <el-form class="custom-form" :model="form" label-width="80px" label-position="right" inline ref="ruleFormRef"
               :rules="rules">
        <el-form-item label="上级菜单" prop="parentid">
          <el-tree-select v-model="form.parentid" :data="treeData" check-strictly :render-after-expand="false"
                          style="width: 180px" clearable/>
        </el-form-item>
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="form.name" style="width: 180px" placeholder="请输入项目名称"
                    clearable></el-input>
        </el-form-item>
        <el-form-item label="项目简称" prop="ziduan">
          <el-input v-model="form.ziduan" style="width: 180px" placeholder="请输入项目简称"
                    clearable></el-input>
        </el-form-item>
        <el-form-item label="项目类别" prop="remark">
          <el-select v-model="form.remark" style="width: 180px" clearable>
            <el-option label="计算项目" value="计算项目"></el-option>
            <el-option label="检测项目" value="检测项目"></el-option>
            <el-option label="检验项目" value="检验项目"></el-option>
            <el-option label="项目类别" value="项目类别"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="编码" prop="bm">
          <el-input v-model="form.bm" style="width: 180px" placeholder="请输入编码(编码唯一)"
                           clearable></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sortindex">
          <el-input-number v-model="form.sortindex" min="0" style="width: 180px" placeholder="请输入序号"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="handleSave(ruleFormRef)">保存</el-button>
          <el-button type="danger" @click="handleCancelSave">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" draggable title="编辑" v-model="dialogVisibleEdit" width="1210px"
               top="5vh" @open="openDialog">
      <el-form :model="form" label-width="80px" lable-width="80px" label-position="right" inline ref="ruleFormRef"
               :rules="rules">

        <el-form-item label="上级菜单" >
          <el-tree-select
              v-model="form.parentid"
              :data="treeData"
              check-strictly
              :render-after-expand="false"
              style="width: 180px"
              clearable
              :disabled="!form.parentid"
          />
        </el-form-item>

        <el-form-item label="项目名称" prop="name">
          <el-input v-model="form.name" style="width: 180px" placeholder="请输入项目名称"
                    clearable></el-input>
        </el-form-item>
        <el-form-item label="项目简称" prop="ziduan">
          <el-input v-model="form.ziduan" style="width: 180px" placeholder="请输入项目简称"
                    clearable></el-input>
        </el-form-item>
        <el-form-item label="项目类别" prop="remark">
          <el-select v-model="form.remark" style="width: 180px" clearable>
            <el-option label="计算项目" value="计算项目"></el-option>
            <el-option label="检测项目" value="检测项目"></el-option>
            <el-option label="检验项目" value="检验项目"></el-option>
            <el-option label="项目类别" value="项目类别"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="编码" prop="bm">
          <el-input v-model="form.bm"  style="width: 180px" placeholder="请输入编码(编码唯一)"
                           clearable></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sortindex">
          <el-input-number v-model="form.sortindex" min="0" style="width: 180px" clearable placeholder="请输入序号"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="handleSaveEdit(ruleFormRef)">保存</el-button>
          <el-button type="danger" @click="handleCancelEdit">取消</el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>

<script setup>
import ButtonBar from '@/components/ButtonBar.vue'

import {
  ref,
  reactive,
  onMounted,
  getCurrentInstance
} from 'vue'

const {
  proxy
} = getCurrentInstance()

import tools from '@/tools'
import {ElMessage, ElMessageBox} from "element-plus";

const cardBodyStyle = ref(tools.style.card)
const inputStyle = ref(tools.style.input)
const dialogVisibleEdit = ref(false)

onMounted(() => {
  handleSearch()
  getTypeData()
  getTreeData()
})

var userName = localStorage.getItem('userDesc')

let dept = localStorage.getItem('dept')
dept = JSON.parse(dept)
let deptCode = dept[0].deptCode
/**
 *   查询
 */

const query = ref({
  name: '',
  bm: ''
})
const tableData = ref([])
const handleSearch = () => {
  currentPage.value = 1
  getTableData()

}

const getTableData = () => {
  var url = 'syi/Zhijianxm/query'
  var param = {
    page: currentPage.value,
    rows: pageSize.value,
    params: JSON.stringify(query.value)
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      tableData.value = response.data.data.records
      totalRows.value = response.data.data.total
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}
/**
 *   查询
 */



const typeData = ref([
  {
    value: '',
    label: '',
    children: []
  }
])

//获取项目类型
const getTypeData = () => {
  var url = 'syi/Zhijianxm/queryType'
  var param = {}
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      response.data.data.forEach(item => {
        typeData.value.push({
          value: item.remark,
          label: item.remark
        })
      })
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }

  })


}

/**
 * 添加时获取树形选择器数据
 *
 */
const treeData = ref([])
const getTreeData = () => {
  var url = 'syi/Zhijianxm/queryName'
  var param = {}
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      treeData.value = []

      response.data.data.forEach(x => {
        const treeDataNode = processNode(x)
        treeData.value.push(treeDataNode.value)
        console.log(treeData.value)
      })
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}

const processNode = (node) => {
  const data = ref({
    label: '',
    value: '',
    children: []
  })
  data.value.label = node.name
  data.value.value = node.id

  if (node.children && node.children.length > 0) {
    node.children.forEach(childNode => {
      // 递归处理子节点
      const childData = processNode(childNode)
      data.value.children.push(childData.value)
    })
  }
  return data
}

/**
 * 分页
 */
const currentPage = ref(1)
const totalRows = ref(0)
const pageSizes = ref([5, 10, 20, 30, 40])
const pageSize = ref(5)
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  getTableData()
}
/**
 * 分页
 */


/**
 * 新增
 */
const dialogVisible = ref(false)
const form = ref({
  id: '',
  parentid: '',
  name: '',
  ziduan: '',
  remark: '',
  sortindex: '',
  bm: '',

})
const ruleFormRef = ref()
const rules = reactive({
  id: [{
    required: true,
    message: '请输入项目ID',
    trigger: 'change' | 'blur'
  }],
  name: [{
    required: true,
    message: '请输入物料名称',
    trigger: 'change' | 'blur'
  }],
  ziduan: [{
    required: true,
    message: '请输入项目简称',
    trigger: 'change' | 'blur'
  }],
  remark: [{
    required: true,
    message: '请选择项目类别',
    trigger: 'change' | 'blur'
  }],
  bm: [{
    required: true,
    message: '请输入项目编码',
    trigger: 'change' | 'blur'
  }],
  sortindex: [{
    required: true,
    message: '请输入项目序号',
    trigger: 'change' | 'blur'
  }]
})

const handleAdd = () => {
  form.value = {
    id: '',
    parentid: '',
    name: '',
    ziduan: '',
    remark: '',
    sortindex: '',
    bm: '',
  }
  dialogVisible.value = true
}
/**
 * 新增
 */


/**
 * 保存、修改、删除
 */

const openDialog = () => {
}

const title = ref('')
const handleSave = (ruleFormRef) => {
  ruleFormRef.validate((valid, fields) => {
    if (valid) {
      var url = 'syi/Zhijianxm/save'
      var param = {
        json: JSON.stringify(form.value),
        userName:userName,
        deptCode:deptCode
      }
      proxy.$axios.post(url, param).then(response => {
        if (response.data.code == 0) {
          form.value = response.data.data
          ElMessage({
            message: '保存成功',
            type: 'success',
          })
          getTableData()
          getTreeData()
          dialogVisible.value = false
        } else {
          // ElMessage.error('操作失败！' + response.data.msg)
          ElMessage({
            message: '操作失败' + response.data.msg,
            type: 'error'
          })
        }
      })

    } else {
      console.log('error submit!', fields)
    }
  })
}

const handleSaveEdit = (ruleFormRef) => {
  if (form.value.id === form.value.parentid) {
    ElMessage({
      message: 'ID 和 ParentID 不能相同！',
      type: 'error'
    });
    return;  // 阻止提交
  }
  ruleFormRef.validate((valid, fields) => {

    if (valid) {
      var url = 'syi/Zhijianxm/edit'
      var param = {
        json: JSON.stringify(form.value),
        userName: userName,
        deptCode: deptCode
      }
      proxy.$axios.post(url, param).then(response => {
        if (response.data.code == 0) {
          form.value = response.data.data
          ElMessage({
            message: '保存成功',
            type: 'success',
          })
          getTableData()
          getTreeData()
          dialogVisibleEdit.value = false
        } else {
          // ElMessage.error('操作失败！' + response.data.msg)
          ElMessage({
            message: '操作失败' + response.data.msg,
            type: 'error'
          })
        }
      })

    } else {
      console.log('error submit!', fields)
    }
  })
}

const handleCancelSave = () => {
  dialogVisible.value = false
}
const handleCancelEdit = () => {
  dialogVisibleEdit.value = false
}
const handleEdit = (row) => {
  dialogVisibleEdit.value = true
  form.value = JSON.parse(JSON.stringify(row))
}
const handleDelete = (row) => {
  if(row.children && row.children.length > 0){
    ElMessage({
      type: 'warning',
      message: '请先删除子节点或者使用批量删除功能',
    })
    return
  }
  ElMessageBox.confirm(
      '此操作将直接删除本条记录?',
      '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
      }
  )
      .then(() => {
        var url = 'syi/Zhijianxm/remove'
        var param = {
          id: row.id,
          userName: userName,
          deptCode: deptCode
        }
        proxy.$axios.post(url, param).then(response => {
          if (response.data.code == 0) {
            ElMessage({
              type: 'success',
              message: '删除成功',
            })
            getTableData()
            getTreeData()
          } else {
            ElMessage({
              type: 'error',
              message: '删除失败' + response.data.msg
            });
          }
        });
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消',
        })
      })
}

/**
 * 保存、修改、删除
 */

const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const handleRemoveBatch = () => {
  console.log('handleRemoveBatch')

  if (multipleSelection.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '请选择要删除的数据!'
    })
    return
  }

  ElMessageBox.confirm('此操作将直接删除该数据, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    var ids = []
    multipleSelection.value.forEach((item, index) => {
      ids.push(item.id)
    })
    var url = 'syi/Zhijianxm/removeBatch'
    var param = {
      ids: JSON.stringify(ids),
      userName: userName,
      deptCode: deptCode
    }
    proxy.$axios.post(url, param).then(response => {
      if (response.data.code == '0') {
        ElMessage({
          type: 'success',
          message: '操作成功!',
        });
        getTableData()
        getTreeData()
        dialogVisible.value = false
      } else {
        ElMessage({
          type: 'error',
          message: '操作失败!' + response.data.msg
        });
      }
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}

const handleEditBatch = () => {
  console.log('handleEditBatch')
  if (multipleSelection.value.length != 1) {
    ElMessage({
      type: 'warning',
      message: '请选择一条数据编辑!'
    })
    return
  }
  handleEdit(multipleSelection.value[0])
}


</script>

<style scoped>

.custom-form {
  height: 300px; /* 设置你想要的高度 */
}
</style>