<script lang="ts" setup>
import { ref, onMounted} from 'vue'
import icon_permission_edit_blue from '@/assets/svg/permission_edit_blue.svg'
import icon_permission_del_blue from '@/assets/svg/permission_del_blue.svg'
import permission_table_edit_blue from '@/assets/svg/permission_table_edit_blue.svg'
import permission_table_del_blue from '@/assets/svg/permission_table_del_blue.svg'
import icon_add from '@/assets/svg/add_white.svg'
import type { FormInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import { ElTable,ElTree } from 'element-plus'
import { getOrganizations,addOrganization,setIsValid,updateOrganizationById,
  deleteById,getOrganizationById } from '@/api/data-visualization/manage/organization'
import { re } from 'mathjs'
const props = defineProps({
  applicationId:String
})
const treeRef = ref<InstanceType<typeof ElTree>>()
const treeData:any = ref([])
const defaultProps = {
  children: 'children',
  label: 'orgname'
}
const treeloading = ref(false);
const hoverNodeId = ref(null);
const currentNodeId = ref(null);
const preventcombo = ref(false)
const dialogVisible = ref(false);
const title = ref('新增企业');
const ruleForm = ref();
const ruleFormRef = ref<FormInstance>()
const rules = ref({
  orgname: [
    { required: true, message: '请输入名称', trigger: 'blur' },
  ],
})
const queryorgname = ref('')
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref([])
const tableData = ref([])
const tableloading = ref(false);
const deptdialog = ref(false);
const depttitle = ref('新增部门')
const deptForm = ref();
const deptFormRef = ref<FormInstance>()
const deptrules = ref({
  orgname: [
    { required: true, message: '请输入名称', trigger: 'blur' },
  ],
})
const handleMouseEnter = (node:any) => {
  hoverNodeId.value = node.key; 
};
const handleMouseLeave = () => {
  hoverNodeId.value = null;
};
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid:any) => {
    if (valid) {
      if(preventcombo.value){
        return
      }
      preventcombo.value = true
      if(ruleForm.value.id !== ''){
        updateOrganizationById(ruleForm.value).then((res:any) => {
          if(res &&res.data.code === '0'){
            ElMessage({
              type: 'success',
              message: '修改成功',
            })
            gettree()
            dialogVisible.value = false
            preventcombo.value = false
          }else{
            ElMessage({
              type: 'error',
              message: '修改失败',
            })
            dialogVisible.value = false
            preventcombo.value = false
            return
          }
          
        })
      }else{
        addOrganization(ruleForm.value).then((res:any) => {
          if(res && res.data.code === '0'){
            ElMessage({
              type: 'success',
              message: '新增成功',
            })
            gettree()
            dialogVisible.value = false
            preventcombo.value = false
          }else{
            ElMessage({
              type: 'error',
              message: '新增失败',
            })
            dialogVisible.value = false
            preventcombo.value = false
            return
          }
        })
      }
    } else {
      return false
    }
  })
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  dialogVisible.value = false
}
const deptsubmitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid:any) => {
    if (valid) {
      if(preventcombo.value){
        return
      }
      preventcombo.value = true
      const params = {
        id:deptForm.value.id,
        appId:deptForm.value.appId,
        orgname: deptForm.value.orgname,
        orgcode: deptForm.value.orgcode,
        orgtype: deptForm.value.orgtype,
        parentid:deptForm.value.parentid,
        manager:deptForm.value.manager,
        description:deptForm.value.description,
        address:deptForm.value.address,
        isvaild:deptForm.value.isvaild,
        contactPhone:deptForm.value.contact_phone,
        contactPerson:deptForm.value.contact_person
      }
      if(deptForm.value.id !== ''){
        updateOrganizationById(params).then(res => {
          ElMessage({
            type: 'success',
            message: '新增成功',
          })
          deptdialog.value = false
          preventcombo.value = false
          getdept(currentNodeId.value)
        })
      }else{
        addOrganization(params).then(res => {
          ElMessage({
            type: 'success',
            message: '新增成功',
          })
          deptdialog.value = false
          preventcombo.value = false
          getdept(currentNodeId.value)
        })
      }
    } else {
      return false
    }
  })
}
const deptresetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  deptdialog.value = false
}
const handleSelectionChange = (val:any) => {
  multipleSelection.value = val
}
onMounted(() => {
  treeData.value = []
  gettree()
})
function gettree(){
  treeloading.value = true
  hoverNodeId.value = null
  currentNodeId.value = null
  queryorgname.value = ''
  treeRef.value!.setCurrentKey(null)
  const params = {
    appId: props.applicationId,
    orgtype:'01',
    parentid:'0',
    orgName:''
  }
  getOrganizations(params).then((res:any) => {
    console.log(res,8798798)
    treeData.value = res.data
    treeloading.value = false
  })
}
function getdept(id:any){
  tableloading.value = true
  const params = {
    appId: props.applicationId,
    orgtype:'02',
    parentid:id,
    orgName:''
  }
  console.log(params,'params')
  getOrganizations(params).then((res:any) => {
    tableData.value = res.data
    tableloading.value = false
    if(currentNodeId.value != null){
      treeRef.value!.setCurrentKey(currentNodeId.value)
    }
  })
}
function querydept(){
  tableloading.value = true
  const params = {
    appId: props.applicationId,
    orgtype:'02',
    parentid:currentNodeId.value,
    orgName:queryorgname.value
  }
  getOrganizations(params).then((res:any) => {
    tableData.value = res.data
    tableloading.value = false
    if(currentNodeId.value != null){
      treeRef.value!.setCurrentKey(currentNodeId.value)
    }
  })
}
function nodeclick(data:any,node:any){
  currentNodeId.value = node.key
  getdept(data.id)
}
function addtree(data:any){
  ruleForm.value = {
    id:'',
    appId:props.applicationId,
    orgname: '',
    orgcode: '',
    orgtype: '01',
    parentid:'0'
  }
  title.value = '新增企业'
  dialogVisible.value = true
}
function edittree(data:any){
  title.value = '修改企业'
  ruleForm.value = JSON.parse(JSON.stringify(data))
  dialogVisible.value = true
}
function deltree(data:any){ 
  ElMessageBox.confirm(
    '确定删除该条信息吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
      deleteById(data.id).then((res:any) => {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        gettree()
      })
    })
    .catch(() => {
      if(currentNodeId.value != null){
      treeRef.value!.setCurrentKey(currentNodeId.value)
    }
    })
}
function setisValid(row:any){
  tableloading.value = true
  const params = {
    id:row.id,
    isvaild:row.isvaild
  }
  setIsValid(params).then((res:any) => {
    console.log(res,'res')
    if(res.code == '0'){
      getdept(currentNodeId.value)
      ElMessage.success('设置成功')
    }else{
      ElMessage.error('设置失败')
    }
    tableloading.value = false
  })
}
function edittable(data:any){ 
  depttitle.value = '修改企业'
  deptForm.value = JSON.parse(JSON.stringify(data))
  deptdialog.value = true
}
function deltable(row:any){ 
  ElMessageBox.confirm(
    '确定删除该条信息吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
      deleteById(row.id).then((res:any) => {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        getdept(currentNodeId.value)
      })
    })
    .catch(() => {

    })
}
function deltables(){
  ElMessageBox.confirm(
    '确定删除该条信息吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      const arr:any = []
      multipleSelection.value.forEach((e:any) => {
        arr.push(e.id)
      });
      deleteById(arr.join()).then((res:any) => {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        getdept(currentNodeId.value)
      })
    })
    .catch(() => {
      
    })
}
function addtable(){
  if(currentNodeId.value == '' || currentNodeId.value == null){
    ElMessage({
      type: 'warning',
      message: '请选择企业！',
    })
    return
  }
  deptForm.value = {
    id:'',
    appId:props.applicationId,
    orgname: '',
    orgcode: '',
    orgtype: '02',
    parentid:currentNodeId.value,
    manager:'',
    description:'',
    address:'',
    isvaild:'1',
    contactPhone:'',
    contactPerson:''
  }
  depttitle.value = '新增部门'
  deptdialog.value = true
}
function handleClose() {
  ruleFormRef.value?.resetFields();
  dialogVisible.value = false;
}
function depthandleClose() {
  deptFormRef.value?.resetFields();
  deptdialog.value = false
}
function formatDateTime(dateArray:any){
  if (!Array.isArray(dateArray) || dateArray.length < 6) return 'Invalid Date'
  
  const pad = (n: number) => n.toString().padStart(2, '0')
  
  return `${dateArray[0]}-${pad(dateArray[1])}-${pad(dateArray[2])} ` +
         `${pad(dateArray[3])}:${pad(dateArray[4])}:${pad(dateArray[5])}`
}
</script>
<template>
   <div class="organization-box">
      <div class="organization-leftbox">
        <div class="leftbox-title">企业列表</div>
        <div class="leftbox-btn" @click="addtree">
          <img src="@/assets/system/add.png" style="margin-right: 5px;" alt="">
          <span>新增企业</span>
        </div>
        <el-tree v-loading="treeloading" ref="treeRef" :data="treeData" node-key="id" :props="defaultProps"
          default-expand-all :expand-on-click-node="false" highlight-current
          @node-click="nodeclick" style="margin-top: 15px;">
          <template #default="{ node, data }">
            <div class="custom-tree-node" @mouseenter="handleMouseEnter(node)"
            @mouseleave="handleMouseLeave()">
            <div>{{ node.label }}</div>
            <div v-show="hoverNodeId === node.key || currentNodeId === node.key" style="display: flex;" >
              <div>
                <el-icon v-if="currentNodeId === node.key" @click.stop="edittree(data)">
                  <icon_permission_edit_blue class="svg-icon"/>
                </el-icon>
                <el-icon v-else @click.stop="edittree(data)">
                  <icon_permission_edit_blue class="svg-icon"/>
                </el-icon>
              </div>
              <div style="margin-left: 8px;">
                <el-icon v-if="currentNodeId === node.key" @click.stop="deltree(data)" style="cursor: pointer;">
                  <icon_permission_del_blue class="svg-icon"/>
                </el-icon>
                <el-icon v-else @click.stop="deltree(data)" style="cursor: pointer;">
                  <icon_permission_del_blue class="svg-icon" />
                </el-icon>
              </div>
            </div>
            </div>
          </template>
        </el-tree>
      </div>
      <div class="organization-rightbox">
        <div class="querybox">
          <div>
            <el-input v-model="queryorgname" placeholder="请输入部门名称" clearable style="width: 200px;margin-right: 10px;" />
            <el-button type="primary" style="min-width: 50px;" @click="querydept">搜索</el-button>
          </div>
          <div>
            <el-button type="primary" style="min-width: 50px;" @click="addtable">
              <el-icon style="margin-right: 3px;">
                <icon_add class="svg-icon" />
              </el-icon>新增
            </el-button>
            <el-button :type="multipleSelection.length>0?'primary':''" :disabled="multipleSelection.length>0?false:true" @click="deltables" style="min-width: 50px;">
              <el-icon style="margin-right: 3px;"><Delete /></el-icon>删除
            </el-button>
          </div>
        </div>
        <el-table class="whitetable" v-loading="tableloading" ref="multipleTableRef" :data="tableData" border style="width: 100%"
          @selection-change="handleSelectionChange" height="calc(100vh - 175px)">
          <el-table-column type="selection" width="55" /> 
          <el-table-column prop="orgcode" label="部门编号" width="90"/>
          <el-table-column prop="orgname" label="部门名称"/>
          <el-table-column prop="manager" label="负责人"/>
          <el-table-column prop="description" label="部门描述"/>
          <el-table-column prop="contact_person" label="联系人"/>
          <el-table-column prop="contact_phone" label="联系电话"/>
          <!-- <el-table-column prop="address" label="联系地址"/> -->
          <el-table-column prop="isvaild" label="是否有效" width="110">
            <template #default="scope">
              <el-switch v-model="scope.row.isvaild" active-value="1" inactive-value="0"  style="margin-right: 10px;" @change="setisValid(scope.row)"/> 
              <span v-if="scope.row.isvaild == '1'" style="color: #0089ff;font-size: 14px;">有效</span>
              <span v-else-if="scope.row.isvaild == '0'" style="color: #bbbfc4;font-size: 14px;">无效</span>
            </template>
          </el-table-column>
          <el-table-column prop="lastmodifier" label="最近修改者"/>
          <el-table-column prop="lastmodifydate" label="最近修改日期" width="170">
            <template #default="scope">
                <span v-if="scope.row.lastmodifydate !== ''">{{formatDateTime(scope.row.lastmodifydate)}}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="80">
            <template  #default="scope">
              <el-icon style="font-size: 16px;margin-right: 18px;cursor: pointer;" @click="edittable(scope.row)">
                <permission_table_edit_blue class="svg-icon"/> 
              </el-icon>
              <el-icon style="font-size: 16px;cursor: pointer;" @click="deltable(scope.row)">
                <permission_table_del_blue class="svg-icon"/> 
              </el-icon>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-dialog v-model="dialogVisible" :title="title" width="30%" :before-close="handleClose">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="80px" class="demo-ruleForm">
          <el-form-item label="企业编号" prop="orgcode">
            <el-input v-model="ruleForm.orgcode" disabled placeholder="系统自动生成" />
          </el-form-item>
          <el-form-item label="企业名称" prop="orgname">
            <el-input v-model="ruleForm.orgname"  placeholder="请输入企业名称" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="resetForm(ruleFormRef)">取消</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
          </span>
        </template>
      </el-dialog>
      <el-dialog v-model="deptdialog" :title="depttitle" width="30%" :before-close="depthandleClose">
        <el-form ref="deptFormRef" :model="deptForm" :rules="deptrules" label-width="80px" class="demo-ruleForm">
          <el-form-item label="部门编号" prop="orgcode">
            <el-input v-model="deptForm.orgcode" disabled placeholder="系统自动生成" />
          </el-form-item>
          <el-form-item label="部门名称" prop="orgname">
            <el-input v-model="deptForm.orgname" placeholder="请输入部门名称" />
          </el-form-item>
          <el-form-item label="负责人" prop="manager">
            <el-input v-model="deptForm.manager" placeholder="请输入负责人" />
          </el-form-item>
          <el-form-item label="部门描述" prop="description">
            <el-input type="textarea" :rows="4" v-model="deptForm.description" placeholder="请输入部门描述"  />
          </el-form-item>
          <el-form-item label="联系人" prop="contact_person">
            <el-input v-model="deptForm.contact_person" placeholder="请输入联系人"  />
          </el-form-item>
          <el-form-item label="联系电话" prop="contact_phone">
            <el-input v-model="deptForm.contact_phone" placeholder="请输入联系电话"  />
          </el-form-item>
          <el-form-item label="联系地址" prop="address">
            <el-input v-model="deptForm.address" placeholder="请输入联系地址"  />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="deptresetForm(deptFormRef)">取消</el-button>
            <el-button type="primary" @click="deptsubmitForm(deptFormRef)">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
</template>

<style lang="less" scoped>
.organization-box{
  width: 100%;
  height: 100%;
  display: flex;
  .organization-leftbox{
    width: 240px;
    height: 100%;
    border-radius: 5px;
    margin-right: 15px;
    background: #ffffff;
    box-shadow: 0px 0px 10px rgba(219, 225, 236, 1);
    .leftbox-title{
      width: 100%;
      height: 44px;
      line-height: 44px;
      font-family: 'Arial Negreta', 'Arial Normal', 'Arial', sans-serif;
      font-weight: 700;
      font-style: normal;
      font-size: 15px;
      color: #000000;
      border-bottom: 1px solid #e8e8e8;
      padding-left: 20px;
    }
    .leftbox-btn{
      width: 200px;
      height: 40px;
      border-width: 1px;
      border-style: solid;
      border-color: #409eff;
      border-radius: 3px;
      font-size: 14px;
      color: #409eff;
      margin: 0 auto;
      margin-top: 15px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
    }
    .leftbox-btn:hover{
      background: rgba(64, 158, 255,0.1);
    }
  }
  .organization-rightbox{
    width: calc(100% - 240px);
    height: 100%;
    background: #ffffff;
    border-radius: 5px;
    padding: 20px;
  }
  .querybox{
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
  }
}
</style>
