<template>
  <div class="businessManagement">
    <div class="businessManagement-left">
      <div class="title flex-between">
        <div class="title_f">{{ $t('personalCenter.bumenguanli') }}</div>
        <div @click="changeDialogVisible('personalCenter.tianjiabumen')" class="title_btn flex-center">
          <img src="/src/assets/imgs/my/jia2@2x.png" alt="">
          <div class="">{{ $t('common.add') }}</div>
        </div>
      </div>
      <el-tree ref="treeRef2" :data="dataSource" node-key="deptId" default-expand-all :expand-on-click-node="false"
        :props="defaultProps" @node-click="handleNodeClick">
        <template #default="{ node, data }">
          <div class="custom-tree-node flex-center-between flex_1">
            <div class="">{{ node.label }}</div>
            <div @click.stop="" v-if="data.isBtn" class="flex-align-center custom-tree-node-right">
              <!-- <el-input v-model="node.label" placeholder="请输入" @keydown="(e) => changeLabel(e, data, node)" /> -->
              <!-- <img @click.stop="changeNode(data, index, 0)" src="/src/assets/imgs/my/jia2@2x.png" alt=""> -->

              <img @click.stop="changeNode(data, index, 1)" src="/src/assets/imgs/my/bianji@2x.png" alt="">
              <img @click.stop="changeNode(data, index, 2)" src="/src/assets/imgs/my/shanchu@2x.png" alt="">
            </div>
          </div>
        </template>
      </el-tree>
    </div>
    <div class="businessManagement-right">
      <div class="title gap10">
        <div class="line_vertical"></div>
        <div class="">{{ $t('personalCenter.wodeyuangong') }}</div>
      </div>
      <div class="flex-center-between businessManagement-right-search">
        <div class="flex-align-center businessManagement-right-search-left">
          <img src="/src/assets/imgs/my/search@2x.png" alt="">
          <input @input="changePhone" type="text" :placeholder="`${$t('personalCenter.qsryssdygsjh')}`"
            v-model="form.userPhone">
        </div>
        <div class="flex-align-center businessManagement-right-search-right">
          <div class="flex-center gradient" @click="changeDialogVisible('personalCenter.tianjiayuangong')">
            <img src="/src/assets/imgs/my/jia1@2x.png" alt="">
            <span>{{ $t('common.add') }}</span>
          </div>
        </div>
      </div>
      <div class="list">
        <div v-for="(item, index) in list" :key="index" class="li">
          <div class="list_left">
            <el-avatar :size="52" :src="item.userAvatar" />
            <div class="list_left_con">
              <div class="">{{ item.nickName }}</div>
              <div class="">{{ item.userPhone || 0 }}</div>
            </div>
          </div>
          <div class="list_right">
            <div @click="changeEmployee(item, index, 1)" class="">
              <img src="/src/assets/imgs/my/jifen@2x.png" alt="">
              <span>{{ $t('personalCenter.fenpei') }}</span>
            </div>
            <div @click="changeEmployee(item, index, 2)" class="">
              <img src="/src/assets/imgs/my/shanchu@2x.png" alt="">
              <span>{{ $t('common.delete') }}</span>
            </div>
          </div>
        </div>
      </div>
      <template v-if="list.length">
        <Pagination :total="form.total" :page-size="form.pageSize" :current-page="form.pageNum"
          @page-change="handlePageChange" />
      </template>
      <el-empty v-else :description="$t('common.empty')" />
    </div>

    <el-dialog v-model="dialogVisible" :title="$t(`${title}`)" width="600">
      <el-form :model="formInline" :rules="rules" label-width="auto" ref="ruleFormRef">
        <template v-if="title == 'personalCenter.tianjiayuangong'">
          <el-row :gutter="0">
            <el-col :span="24">
              <el-form-item :label="$t('personalCenter.bumen')" prop="deptId">
                <el-tree-select v-model="formInline.deptId" :data="dataSource" :props="defaultProps"
                  :placeholder="$t('personalCenter.qxebm')" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="0">
            <el-col :span="24">
              <el-form-item :label="$t('personalCenter.yuangong')" prop="userPhone">
                <el-select v-model="formInline.userPhone" filterable remote reserve-keyword
                  :placeholder="$t('personalCenter.qsryssdygsjh')" :remote-method="remoteMethod">
                  <el-option v-for="item in options" :key="item.userPhone" :label="item.nickName"
                    :value="item.userPhone" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="0">
            <el-col :span="24">
              <el-form-item :label="$t('personalCenter.kfpmb')">
                <el-input v-model="formInline.number" :placeholder="$t('common.placeholderInput')" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="0">
            <el-col :span="24">
              <el-form-item :label="$t('personalCenter.mbsl')" prop="points">
                <el-input v-model="formInline.points" :placeholder="$t('common.placeholderInput')" type="number"
                  :min="1" :max="formInline.number" />
              </el-form-item>
            </el-col>
          </el-row>
           <el-text class="mx-1" type="danger">*{{ $t('personalCenter.zdfp') }}</el-text>
        </template>
        <template v-else-if="title == 'personalCenter.fenpeimibi'">
          <el-row :gutter="0">
            <el-col :span="24">
              <el-form-item :label="$t('personalCenter.bumen')" prop="deptId">
                <el-tree-select disabled v-model="formInline.deptId" :data="dataSource" :props="defaultProps"
                  :placeholder="$t('common.qingxuanze')" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="0">
            <el-col :span="24">
              <el-form-item :label="$t('personalCenter.yuangong')" prop="userPhone">
                <el-select disabled v-model="formInline.userPhone" filterable remote reserve-keyword
                  :placeholder="$t('common.placeholderInput')" :remote-method="remoteMethod">
                  <el-option v-for="item in options" :key="item.userPhone" :label="item.nickName"
                    :value="item.userPhone" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="0">
            <el-col :span="24">
              <el-form-item :label="$t('personalCenter.kfpmb')">
                <el-input v-model="formInline.number" :placeholder="$t('common.placeholderInput')" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="0">
            <el-col :span="24">
              <el-form-item :label="$t('personalCenter.mbsl')" prop="points">
                <el-input v-model="formInline.points" :placeholder="$t('common.placeholderInput')" type="number"
                  :min="1" :max="formInline.number" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-text class="mx-1" type="danger">*{{ $t('personalCenter.zdfp') }}</el-text>
          
        </template>
        <el-row :gutter="0" v-else>
          <el-col :span="24">
            <el-form-item :label="$t('personalCenter.bumen')" prop="deptName">
              <el-input v-model="formInline.deptName" :placeholder="$t('personalCenter.qsrbmmc')" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer flex-center">
          <el-button  @click="resetForm">{{ $t('common.cancel') }}</el-button>
          <el-button class="gradient" type="primary" @click="confirmSubAccount(ruleFormRef)">{{ $t('common.confirm') }}</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>
<script setup lang="ts">

import { ref, onMounted } from 'vue';

import { deptList, employeeList, applyDept, deleteDept, addSubAccount, deleteSubAccount, selectUserByPhone, allocatePoints, getAvailablePoints, uploadDept } from '@/api/my';

import DGTMessage from '@/utils/message'

import Pagination from '@/components/Pagination.vue'

import { useI18n } from 'vue-i18n'

const { t } = useI18n()

import { useAppStore } from '@/pinia/appStore'

const appStore = useAppStore();

const list = ref([]);

const dataSource = ref([])

const defaultProps = {
  children: 'children',
  label: 'deptName',
  value: 'deptId'
}

const form = ref({
  total: 0,
  pageSize: 10,
  pageNum: 1,
  userPhone: ''
})

const title = ref('personalCenter.tianjiayuangong')

const dialogVisible = ref(false);

const ruleFormRef = ref(null);

const formInline = ref({
  deptId: '',
  userPhone: '',
  deptName: '',
  userId: null,
  points: 0,
  number: 0
})

const options = ref([])

const rules = ref({
  deptId: [{ required: true, message: t('personalCenter.qxzbm'), trigger: 'change' }],
  userPhone: [{ required: true, message: t('personalCenter.qxzyg'), trigger: 'change' }],
  deptName: [{ required: true, message: t('personalCenter.qsrbmmc'), trigger: 'blur' }],
  points: [{ required: true, message: t('personalCenter.qsryfpdmbsl'), trigger: 'blur' }]
})

const changeDialogVisible = async (txt) => {
  let res = await getAvailablePoints();
  formInline.value.number = res.data.points;
  title.value = txt;
  dialogVisible.value = true;
}

const changeEmployee = async (item, index, type) => {
  if (type == 1) {
    formInline.value.userId = item.userId;
    formInline.value.points = item.points;
    formInline.value.deptId = item.deptId;
    formInline.value.userPhone = item.userPhone;
    changeDialogVisible('personalCenter.fenpeimibi');
  } else if (type == 2) {
    let res = await deleteSubAccount(item.userId)
    if (res.code == 200) {
      getemployeeList();
    }
  }
}

// 添加员工
const confirmSubAccount = async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {

      let api = title.value == 'personalCenter.tianjiayuangong' ? addSubAccount(formInline.value) : title.value == 'personalCenter.tianjiabumen' ? applyDept({
        deptName: formInline.value.deptName,
        parentId: formInline.value.deptId
      }) : title.value == 'personalCenter.fenpeimibi' ? allocatePoints({
        userId: formInline.value.userId,
        points: formInline.value.points
      }) : uploadDept({
        deptName: formInline.value.deptName,
        deptId: formInline.value.deptId
      })
      let res = await api;
      if (res.code === 200) {
        DGTMessage.success(`${t('common.success')}`)
        title.value == 'personalCenter.tianjiayuangong' ? getemployeeList() : getList();
        resetForm()

      }

    }
  })

}

const resetForm = () => {
  dialogVisible.value = false;
  setTimeout(() => {
    formInline.value.deptId = null;
    formInline.value.deptName = '';
    formInline.value.parentId = null;
    formInline.value.points = 0;
    formInline.value.userPhone = '';
  }, 500)
}

// 搜索员工
const remoteMethod = async (query: string) => {
  if (query && query.length == 11 || isValidEmail(query)) {
    let res = await selectUserByPhone({
      userPhone: query
    });
    options.value = res.data ? [res.data] : [];
  } else {
    options.value = [];
  }
}

const isValidEmail = (email) => {
  // 核心正则表达式，兼顾常见邮箱格式规范
  const emailReg = /^[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)*@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)*\.[a-zA-Z]{2,}$/;

  // 先判断是否为字符串，避免非字符串类型传入导致错误
  if (typeof email !== 'string') {
    return false;
  }

  // 去除首尾空格后验证
  return emailReg.test(email.trim());
}

const changePhone = (e) => {
  if (e.target.value.length == 11 || e.target.value.length == 0 || isValidEmail(e.target.value)) {

  }
  getemployeeList();
}

const handlePageChange = (pageNum, pageSize) => {
  form.value.pageNum = pageNum;
  if(pageSize)form.value.pageSize = pageSize;
  getemployeeList();
}

const getList = async () => {
  let res = await deptList({ pageSize: 100 });
  addFieldsToAllElements(res.rows);
  dataSource.value = res.rows;
  getemployeeList();
}

const addFieldsToAllElements = (arr) => {

  // 遍历当前层级的每一个元素
  arr.map(element => {
    // 给当前元素添加字段
    element.isBtn = false;
    element.isIpt = false;

    // 如果当前元素有children，并且children是数组，就递归处理下一层
    if (element.children && Array.isArray(element.children)) {
      addFieldsToAllElements(element.children);
    }
  });
}

const getemployeeList = async () => {
  let res = await employeeList(form.value);
  list.value = res.rows;
  form.value.total = res.total;
}

const changeNode = async (item, index, type) => {
  formInline.value.deptId = item.deptId
  if (type == 0) {
    changeDialogVisible('personalCenter.tianjiabumen')
  } else if (type == 1) {
    formInline.value.deptName = item.deptName
    changeDialogVisible('personalCenter.bianjibumen')
  } else if (type == 2) {
    let res = await deleteDept(item.deptId);
    if (res.code === 200) {
      DGTMessage.success(`${t('common.success')}`)
      getList()
    }
  }
}

const changeLabel = async (e, data, node) => {
  console.log(e, data, node);
}

const handleNodeClick = (data) => {
  // console.log(data.isBtn = true)
  data.isBtn = !data.isBtn
}

onMounted(() => {
  getList()
})
</script>
<style lang="scss" scoped>
.businessManagement {
  padding: 16px 0;
  display: flex;

  .businessManagement-left {
    width: 300px;
    padding: 16px;
    background: #F5F7FA;
    border-radius: 16px;

    .title {
      margin-bottom: 16px;

      &_f {
        color: #262626;
        font-size: 20px;
        font-weight: bold;
      }
    }

    .title_btn {
      width: 62px;
      height: 28px;
      cursor: pointer;
      background: #FFFFFF;
      color: #2D71FF;
      font-size: 14px;
      border-radius: 4px;

      img {
        width: 14px;
        height: 14px;
        margin-right: 4px;
      }
    }

    :deep(.el-tree) {
      background: transparent;
    }
  }

  .businessManagement-right {
    margin-left: 16px;
    flex: 1;

    .title {
      color: #333333;
      font-size: 20px;
      font-weight: bold;
    }

    .businessManagement-right-search {
      padding: 16px 0;

      .businessManagement-right-search-left {
        width: 420px;
        height: 32px;
        padding: 0 12px;
        background: #F5F7FA;
        border-radius: 4px;
        border: 1px solid #DCDFE6;

        img {
          width: 16px;
          height: 16px;
          margin-right: 4px;
        }

        input {
          flex: 1;
          font-size: 14px;
          border: none;
          outline: none;
          background: transparent;
        }
      }

      .businessManagement-right-search-right {
        div {
          color: #FFFFFF;
          font-size: 14px;
          width: 78px;
          height: 32px;
          border-radius: 4px;
          cursor: pointer;

          img {
            width: 14px;
            height: 14px;
          }
        }
      }
    }
  }
}

.custom-tree-node {
  height: 30px;
  margin-top: 4px;
  color: #262626;
  font-size: 14px;

  .custom-tree-node-right {
    gap: 8px;

    img {
      width: 14px;
      height: 14px;
    }
  }
}

.list {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  gap: 16px;

  .li {
    width: 420px;
    padding: 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: #F5F7FA;
    border-radius: 16px;

    .list_left {
      display: flex;
      align-items: center;

      .list_left_con {
        margin-left: 10px;

        div {
          &:first-child {
            font-size: 18px;
            margin-bottom: 4px;
            font-weight: bold;
          }

          &:last-child {
            color: #666666;
            font-size: 14px;
          }
        }
      }
    }

    .list_right {
      display: flex;
      align-items: center;
      gap: 8px;

      div {
        display: flex;
        cursor: pointer;
        align-items: center;
        justify-content: center;
        min-width: 62px;
        height: 32px;
        padding: 0 8px;
        background: #FFFFFF;
        border-radius: 4px;
        font-size: 14px;
        color: #2D71FF;

        img {
          width: 14px;
          height: 14px;
          margin-right: 4px;
        }

        &:last-child {
          color: #E43434;
        }
      }
    }
  }
}
</style>