<script setup>
import form_data from '../jsxx/config.js'
import AddAndEdit from '../jsxx/components/AddAndEdit.vue'
import DetailInfo from '../jsxx/components/DetailInfo.vue'
import { area_list, org_list, org_tree_list, user_list } from '../jsxx/api'
import PrevIcon from '@/components/EpPagination/PrevIcon.vue'
import NextIcon from '@/components/EpPagination/NextIcon.vue'
import { user } from '@/store/index'
const formData = ref(form_data)

const ruleFormRef = ref(null)
const ruleForm = ref({
  area_id: '',
  uo_id_1: '',
  uom_zw: '',
})

const handleReset = (formEl) => {
  if (!formEl)
    return
  formEl.resetFields()
  initData()
}

const areaData = ref([])
const treeData = ref([])
const departmentData = ref([])
const defaultProps = {
  children: 'children',
  label: 'label',
}
const mineStatus = ref([])
const mineStatusValue = ref([])
const tree = ref(null)

initKeyData()
async function initKeyData() {
  const res1 = await area_list({ pid: '2615' })
  if (res1.code == 1)
    areaData.value = res1.data.area

  const res2 = await org_tree_list()
  if (res2.code == 1)
    treeData.value = res2.data.list_tree

  const res3 = await org_list({ uo_pid: '0', limit: '100' })
  if (res3.code == 1)
    departmentData.value = res3.data.page_data
}

const selectChange = (e) => {
  const arrNew = []
  const dataLength = mineStatusValue.value.length
  const eleng = e.length
  for (let i = 0; i < dataLength; i++) {
    for (let j = 0; j < eleng; j++) {
      if (e[j] === mineStatusValue.value[i].label)
        arrNew.push(mineStatusValue.value[i])
    }
  }
  tree.value.setCheckedNodes(arrNew) // 设置勾选的值
}

const handleCheckChange = () => {
  const res = tree.value.getCheckedNodes(true, true) // 这里两个true，1. 是否只是叶子节点 2. 是否包含半选节点（就是使得选择的时候不包含父节点）
  mineStatus.value = []
  res.forEach((item) => {
    mineStatus.value.push(item.label)
  })
  mineStatusValue.value = [...res]
}

const handleNodeClick = (e) => {
  mineStatus.value = [e.label]
  mineStatusValue.value = [e.id]
  initData()
}

const handleChange = () => {
  tree.value.setCurrentKey(null)
  mineStatus.value = []
  mineStatusValue.value = []
  initData()
}

const searchKey = ref('')
const initSearchKey = (val) => {
  searchKey.value = val
  initData()
}

const columnData = ref([
  {
    name: 'ID',
    key: 'user_id',
  },
  {
    name: '姓名',
    key: 'user_realname',
  },
  {
    name: '账号',
    key: 'user_name',
  },
  {
    name: '联系电话',
    key: 'ue_user_phone',
  },
  {
    name: '单位/部门/职位',
    key: 'dwbmzw',
  },
])
const tableData = ref([])
const total = ref(0)
const limit = ref(10)
const currentPage = ref(1)
initData()
async function initData() {
  const obj = {
    keyword: searchKey.value,
    limit: limit.value,
    page: currentPage.value,
    user_role_id: 'ju',
    uom_zw: ruleForm.value.uom_zw,
    uo_id_1: mineStatusValue.value.join(','),
  }
  const res = await user_list(obj)
  if (res.code == 1) {
    tableData.value = []
    res.data.page_data.map((item) => {
      const arr = []
      item.my_org.map((val) => {
        arr.push(`${val.uo_name_0}/${val.uo_name_1}/${val.uom_zw}`)
      })
      const obj = {
        user_id: item.user_id,
        user_realname: item.user_realname,
        user_name: item.user_name,
        ue_user_phone: item.user_ext.ue_user_phone,
        dwbmzw: arr.join('，'),
      }
      tableData.value.push(obj)
    })
    total.value = parseInt(res.data.total_rows)
  }
}
function handleCurrentChange(val) {
  currentPage.value = val
  initData()
}

const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogType = ref('')
const userId = ref('')
const handleAdd = () => {
  dialogVisible.value = true
  dialogTitle.value = '新增'
  dialogType.value = 1
}

const handleEdit = (val) => {
  dialogVisible.value = true
  dialogTitle.value = '编辑'
  dialogType.value = 1
  userId.value = val.user_id
}

const handleClose = (type) => {
  dialogVisible.value = false
  dialogTitle.value = ''
  dialogType.value = ''

  if (type == 1)
    initData()
}

const handleDetail = (val) => {
  dialogVisible.value = true
  dialogType.value = 2
  userId.value = val.user_id
}

let multipleSelection = $ref([])
const handleSelect = (val) => {
  multipleSelection = []
  val.forEach((i) => {
    multipleSelection.push(i.user_id)
  })
}

const handleExport = () => {
  const link = `${window.GLOBAL_CONFIG.uc}/user/main/index?user_role_id=ju&api=xls&page=1&site=myxjyszptx&limit=10000&token=${user.value.token}&uid=${multipleSelection}`
  window.open(link, '_blank')
  console.log(link, 345)
}
</script>

<template>
  <div class="jsxxContent card h-full">
    <div class="searchDiv flex justify-between">
      <el-form ref="ruleFormRef" label-position="top" :model="ruleForm" :inline="true" label-width="100px">
        <el-form-item label="区域" prop="area_id">
          <el-select v-model="ruleForm.area_id" filterable clearable>
            <el-option v-for="(item, index) in areaData" :key="index" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="uo_id_1">
          <el-select v-model="mineStatus" placeholder="请选择" clearable @change="selectChange" @clear="handleChange">
            <el-option :value="mineStatusValue" style="height: auto">
              <el-tree ref="tree" default-expand-all :data="treeData" node-key="id" highlight-current :props="defaultProps" @check-change="handleCheckChange" @node-click="handleNodeClick" />
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="职位" prop="uom_zw">
          <el-input v-model="ruleForm.uom_zw" />
        </el-form-item>
      </el-form>
      <div>
        <el-button size="small" type="primary" @click="initData">
          查询
        </el-button>
        <br>
        <el-button size="small" type="primary" plain class="mt-10px" @click="handleReset(ruleFormRef)">
          重置
        </el-button>
      </div>
    </div>
    <div class="content">
      <div class="flex justify-between mt-20px mb-20px">
        <div>
          <!-- <el-button class="_" type="primary">批量导入</el-button> -->
          <!-- <el-button class="_" type="primary" @click="handleAdd">新增</el-button> -->
          <el-button class="_" type="primary" @click="handleExport">
            导出
          </el-button>
        </div>
        <div class="flex items-center space-x-4">
          <search-keys @init="initSearchKey" />
          <!-- <el-button class="_" type="danger">删除</el-button> -->
        </div>
      </div>

      <table-column :column-data="columnData" :table-data="tableData" :delete-btn="false" @select="handleSelect" @edit="handleEdit" @detail="handleDetail" />

      <div class="flex_center mt-6 pb-12">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="limit" layout="total, prev, pager, next, jumper" :total="total" :prev-icon="PrevIcon" :next-icon="NextIcon" @current-change="handleCurrentChange" />
      </div>
    </div>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" :width="dialogType == 1 ? '680px' : '1100px'" :class="dialogType == 1 ? '_' : 'detailDialog'" :close-on-click-modal="dialogType == 1 ? false : true" @close="handleClose">
      <AddAndEdit v-if="dialogType == 1" :data="formData" :user-id="userId" :area-data="areaData" :sydw-data="departmentData" show-type="jdxx" @close="handleClose" />
      <DetailInfo v-if="dialogType == 2" :data="formData" :user-id="userId" show-type="jdxx" />
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
@use "~/styles/button.scss";
@use "~/styles/dialog.scss";
@use "~/styles/pagination.scss";
.searchDiv {
  border-bottom: 1px solid #ebf3ff;
  :deep(.el-form) {
    .el-form-item__label {
      font-size: 14px;
      color: #3f3f44;
      font-weight: 600;
      margin-bottom: 5px;
    }
    .el-form-item__content {
      .el-input,
      .el-input__wrapper {
        width: 100%;
        box-shadow: none;
        outline: none;
        border-radius: 8px;
      }
      .el-input {
        border: 1px solid #ebf3ff;
      }
    }
  }
  .el-button--small {
    height: 34px;
    padding: 6px 22px;
    border-radius: 10px;
    &.is-plain {
      background: none;
      color: #3f8cff;
    }
  }
}
:deep(.detailDialog) {
  border-radius: 16px;
}
</style>
