<template>
  <div style="display: flex">
    <div class="menus-container">
      <div class="toolbar">
        <div class="inner-toolbar">
          <div class="toolbar-btns">
            <el-button size="small" v-if="checkPermission(['branch:add'])&& store.state.user.user.founder!==1" type="primary" @click="handleAddBranch">{{$t('add')}}</el-button>
          </div>
        </div>
      </div>
      <div style="overflow: auto; height: 540px; background: #fff">
        <el-tree :data="deptList" node-key="identifier" :expand-on-click-node="false" default-expand-all>
          <template #default="{  data }">
            <span class="custom-tree-node" @click="handleEditBranch(data)">
              <span>{{ data.name }}</span>
            </span>
          </template>
        </el-tree>
      </div>
      <el-dialog :title="$t('add')" v-model="dialogVisible" width="500px" :close-on-click-modal="false" :close-on-press-escape="false" class="!rounded-lg">
        <el-form :model="deptForm" ref="deptFormRef" label-width="130px">
          <el-form-item :label="$t('dept_names')" prop="name">
            <el-input v-model="deptForm.name" :maxlength="6"></el-input>
          </el-form-item>
          <el-form-item :label="$t('dept_sn')" prop="sn">
            <el-input v-model="deptForm.sn" :maxlength="50"></el-input>
          </el-form-item>
          <el-form-item :label="$t('dept_auth_regular')" prop="auth_regular">
            <el-cascader
              v-model="deptForm.parent_id"
              :options="deptList"
              :props="{
                label: 'name',
                value: 'id',
                emitPath: false,
                checkStrictly: true,
              }"
              clearable
            ></el-cascader>
          </el-form-item>
          <!--   <el-form-item label="所在地区" prop="auth_regular">
              <en-region-picker :api="MixinRegionApi" :default="defaultRegions"
                @changed="(object) => { deptForm.region = object.last_id }" />
            </el-form-item> -->
          <el-form-item :label="$t('dept_type')" prop="auth_regular">
            <el-select v-model="deptForm.type" :placeholder="$t('change')+$t('dept_type')" size="small">
              <el-option v-for="item in deptType" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('dept_sort')" prop="sort">
            <el-input v-model="deptForm.sort" :maxlength="2"></el-input>
          </el-form-item>
          <el-form-item :label="$t('dept_remark')" prop="remark">
            <el-input v-model="deptForm.remark" type="textarea" :autosize="{ minRows: 3, maxRows: 4 }" :placeholder="$t('change')+$t('dept_remark')"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">{{$t('cancel')}}</el-button>
          <el-button type="primary" @click="submitBranchForm">{{$t('submit')}}</el-button>
        </template>
      </el-dialog>
    </div>
    <div class="basicsetting-container">
      <el-form class="form" :model="deptForm" ref="deptFormRef" label-width="120px" v-if="dialogEditVisible">
        <el-form-item :label="$t('dept_names')" prop="name">
          <el-input v-model="deptForm.name" :maxlength="6"></el-input>
        </el-form-item>
        <el-form-item :label="$t('dept_sn')" prop="sn">
          <el-input v-model="deptForm.sn" :maxlength="50"></el-input>
        </el-form-item>
          <el-form-item :label="$t('dept_auth_regular')" prop="parent_id">
          <el-cascader
          disabled
            v-model="deptForm.parent_id"
            :options="deptList"
            :props="{
              label: 'name',
              value: 'id',
              emitPath: false,
              checkStrictly: true,
            }"
            clearable
          ></el-cascader>
        </el-form-item>
        <!--    <el-form-item label="所在地区" prop="region">
            <en-region-picker :api="MixinRegionApi" :default="defaultRegions"
              @changed="(object) => { deptForm.region = object.last_id }" />
          </el-form-item> -->
        <!-- <el-form-item label="部门类型" prop="type">
          <el-select v-model="deptForm.type" placeholder="请选择部门类型" size="small">
            <el-option v-for="item in deptType" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item> -->
        <el-form-item :label="$t('dept_sort')" prop="sort">
          <el-input v-model="deptForm.sort" :maxlength="2"></el-input>
        </el-form-item>
        <el-form-item :label="$t('dept_remark')" prop="remark">
          <el-input v-model="deptForm.remark" type="textarea" :autosize="{ minRows: 3, maxRows: 4 }" :placeholder="$t('place')+$t('dept_remark')"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitBranchForm" v-if="checkPermission(['branch:edit']) && store.state.user.user.founder!==1">{{$t('save')}}</el-button>
          <el-button type="danger" @click="handleDeleteBranch" v-if="checkPermission(['branch:del']) && store.state.user.user.founder!==1">{{$t('delete')}}</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
  
  <script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import * as API_Setting from '@/api/setting';
import { useStore } from 'vuex';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();
const store = useStore();
const defaultRegions = ref<any>(null);
const deptList = ref([]);
interface DeptType {
  value: string;
  default_flag: boolean;
  label:string
}
const deptType = ref<DeptType[]>([]);
const deptForm = ref<any>({
  sort: 1,
  name: '',
  sn: '',
  parent_id: '',
  type: '',
  remark: '',
});
const dialogVisible = ref(false);
const dialogEditVisible = ref(false);
const deptFormRef = ref();

const checkPermission = (permissions: string[]): boolean => {
  return true;
};

const GET_DictDataInfo = () => {
  API_Setting.getDictDataInfo('erp_dept_type').then((response) => {
    deptType.value = response;
  });
};

/* 处理树形数据 */
let buildTree = function buildTree(list, parent_id) {
  const tree: any = [];
  for (let i = 0; i < list.length; i++) {
    if (list[i].parent_id === parent_id) {
      const node = {
        id: list[i].id,
        parent_id: list[i].parent_id,
        name: list[i].name,
        create_time: list[i].create_time,
        remark: list[i].remark,
        sn: list[i].sn,
        sort: list[i].sort,
        type: list[i].type,
        region_ids: list[i].region_ids,
        children: buildTree(list, list[i].id),
      };
      tree.push(node);
    }
  }
  return tree;
};
const GET_DeptList = () => {
  API_Setting.getDeptList({ company_id: store.state.companId }).then((response) => {
    deptList.value = buildTree(response, '0');
    console.log(deptList.value);
  });
};

const handleAddBranch = () => {
  deptForm.value = {
    sort: 1,
    name: '',
    sn: '',
    parent_id: '',
    remark: '',
    type: deptType.value.find((sc: any) => sc.default_flag === true)?.value || 'MANAGER',
  };
  defaultRegions.value = [];
  dialogEditVisible.value = false;
  dialogVisible.value = true;
};

const handleEditBranch = (row: any) => {
  deptForm.value = JSON.parse(JSON.stringify(row)); // 创建深拷贝
  defaultRegions.value = row.region_ids ? [...row.region_ids] : [];
  dialogEditVisible.value = true;
};

const handleDeleteBranch = () => {
  ElMessageBox.confirm(t('del_info')+'？', t('prompt'), { type: 'warning' })
    .then(() => {
      const { id } = deptForm.value;
      API_Setting.deleteDept({ id }).then(() => {
        ElMessage.success(t('del_success'));
        dialogEditVisible.value = false;
        GET_DeptList();
      });
    })
    .catch(() => {});
};

const submitBranchForm = () => {
  const { id, region } = deptForm.value;
  const params = { ...deptForm.value };
  /* if (!region) {
    ElMessage.error('请选择所在地区！');
    return false;
  } */
  if (id) {
    API_Setting.editDept(params).then(() => {
      dialogVisible.value = false;
      ElMessage.success(t('edit_success')+'！');
      GET_DeptList();
    });
  } else {
    API_Setting.addDept(params).then(() => {
      dialogVisible.value = false;
      ElMessage.success(t('add_success')+'！');
      GET_DeptList();
    });
  }
};

onMounted(() => {
  GET_DeptList();
  GET_DictDataInfo();
});
</script>
  <style scoped>
:deep(.w-e-text-container) {
  min-height: 200px !important;
}

:deep(.w-e-full-screen-container) {
  z-index: 3000;
}

.toolbar {
  display: flex;
  align-items: center;
  height: 44px;
  border-bottom: 1px solid #e6ebf5;
  background-color: #fff;
}

.inner-toolbar {
  padding: 0 20px;
}

.inner-toolbar .categary {
  padding-right: 10px;
  font-size: 14px;
}

.face-image {
  display: block;
  width: 50px;
  height: 50px;
  margin: 0 auto;
}

:deep(.el-dialog__body) {
  padding: 10px 20px;
}

.basicsetting-container {
  background-color: #fff;
  flex: 2;
  margin: 10px 0 0 10px;
}

.basicsetting-container .form {
  padding-top: 20px;
  width: 500px;
}

.menus-container {
  flex: 1;
  margin: 10px 0 0 10px;
}

.menus-container :deep(.el-tree) {
  width: 500px;
}

.menus-container :deep(.el-icon-minus) {
  color: #f56c6c;
}

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