<template>
  <header>
    <h3 style="margin: 0px; padding: 5px 0px 9px 0px">
      {{ $t("lang.OrganizationEditPanel.departmentManagement") }}
    </h3>
    <a-divider style="margin: 0px" />
  </header>
  <div style="margin-top: 8px">
    <a-button type="primary" @click="editOrganization(true)">
      {{ $t("lang.OrganizationEditPanel.newDepartment") }}
    </a-button>
    <a-button type="dashed" style="margin-left: 8px" @click="refreshData">
      {{ $t("lang.OrganizationEditPanel.refresh") }}
    </a-button>
    <a-select
      v-model:value="clientIdStr"
      show-search
      option-filter-prop="label"
      style="width: 50%; margin-left: 16px"
      placeholder="请选择公司"
      :options="companies.map((item) => ({ value: item.id, label: item.name }))"
      @change="getClientId"
    />
    <a-button type="primary" style="margin-left: 8px" @click="editClient">
      编辑公司
    </a-button>
  </div>

  <a-table
    style="margin-top: 6px"
    :columns="columns"
    :data-source="dataSource"
    :pagination="false"
    :scroll="{ y: 440 }"
    filter-search
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.dataIndex === 'operation'">
        <div class="editable-row-operations">
          <span>
            <a @click="editOrganization(false, record.key)">{{
              $t("lang.OrganizationEditPanel.edit")
            }}</a>
          </span>
          <span>
            <a-popconfirm
              title="确定删除吗！"
              ok-text="确定"
              cancel-text="取消"
              @confirm="deleteOrganization(record.key)"
            >
              <a style="color: red">删除</a>
            </a-popconfirm>
          </span>
        </div>
      </template>
    </template>
  </a-table>

  <a-drawer
    v-model:open="editVisible"
    :title="drawerTitle"
    :width="500"
    placement="right"
  >
    <div class="form-group">
      <label>{{ $t("lang.OrganizationEditPanel.corporateName") }}</label>
      <a-input v-model:value="organization.clientName" disabled />
    </div>
    <div class="form-group">
      <label>{{ $t("lang.OrganizationEditPanel.departmentNumber") }}</label>
      <a-input v-model:value="organization.no" />
    </div>
    <div class="form-group">
      <label>{{ $t("lang.OrganizationEditPanel.departmentName") }}</label>
      <a-input v-model:value="organization.name" />
    </div>
    <div class="form-group">
      <label>{{ $t("lang.OrganizationEditPanel.superiorDepartment") }}</label>
      <a-tree-select
        v-model:value="organization.parentId"
        show-search
        allow-clear
        style="width: 100%"
        :tree-data="organizations"
        tree-node-filter-prop="label"
        :dropdown-style="{ maxHeight: '300px', overflow: 'auto' }"
        @change="parentOrganizationValueChanged"
      />
      <!-- <SearchWidget
        info-window-no="20220420_233656"
        :field-value="parentOrganizationFieldValue"
        :title-name="$t('lang.OrganizationEditPanel.departmentInquiry')"
        display-name="name"
        :where-clause-source="parentOrganizationAdditionHql"
        @value-changed="parentOrganizationValueChanged"
      /> -->
    </div>
    <div class="form-group">
      <label>{{ $t("lang.OrganizationEditPanel.departmentProfile") }}</label>
      <textarea
        v-model="organization.description"
        class="form-control"
        rows="3"
      />
    </div>
    <div class="form-group">
      <label>{{ $t("lang.OrganizationEditPanel.departmentManager") }}</label>
      <div>
        <a-select
          v-model:value="organization.userIds"
          style="width: 100%"
          mode="multiple"
          :filter-option="false"
          :field-names="{ label: 'text', value: 'id' }"
          :not-found-content="fetching ? undefined : null"
          :options="userList"
          show-search
          @search="fetchUser"
          @change="getOrgUsers"
          @focus="focusUser('')"
        >
          <template v-if="fetching" #notFoundContent>
            <a-spin size="small" />
          </template>
        </a-select>
      </div>
    </div>
    <template #footer>
      <a-button v-if="isCreate" type="primary" @click="createNew(organization)">
        创建
      </a-button>
      <a-button
        v-else
        type="primary"
        @click="updateOrganization(organization.id)"
      >
        {{ $t("lang.OrganizationEditPanel.save") }}
      </a-button>
      <a-button
        v-if="!isCreate"
        danger
        style="margin-left: 8px"
        @click="hiddenDepartment(organization)"
      >
        隐藏部门
      </a-button>
    </template>
  </a-drawer>
  <a-drawer
    v-model:open="isEditClient"
    title="编辑公司"
    :width="500"
    placement="right"
  >
    <div class="form-group">
      <label>公司ID</label>
      <a-input v-model:value="client.id" disabled />
    </div>
    <div class="form-group">
      <label>{{ $t("lang.OrganizationEditPanel.corporateName") }}</label>
      <a-input v-model:value="client.name" />
    </div>
    <div class="form-group">
      <label>{{ $t("lang.OrganizationEditPanel.companyNumber") }}</label>
      <a-input v-model:value="client.no" />
    </div>
    <div class="form-group">
      <label>公司简介</label>
      <textarea v-model="client.description" class="form-control" rows="3" />
    </div>
    <div class="form-group">
      <label>{{ $t("lang.OrganizationEditPanel.departmentManager") }}</label>
      <div>
        <a-select
          v-model:value="client.userIds"
          style="width: 100%"
          mode="multiple"
          :filter-option="false"
          :field-names="{ label: 'text', value: 'id' }"
          :not-found-content="fetching ? undefined : null"
          :options="userList"
          show-search
          @search="fetchUser"
          @change="getClientUsers"
          @focus="focusUser('')"
        >
          <template v-if="fetching" #notFoundContent>
            <a-spin size="small" />
          </template>
        </a-select>
      </div>
    </div>
    <template #footer>
      <a-button type="primary" @click="updateClient(client.id)">
        {{ $t("lang.OrganizationEditPanel.save") }}
      </a-button>
    </template>
  </a-drawer>
  <Loading v-if="loading" />
</template>

<script setup>
import Common from '../common/Common.js';
import { Notify } from 'pc-component-v3';
import { ref, onMounted, getCurrentInstance } from 'vue';

import {
  columns,
  create,
  update,
  getCompony,
  getClientInfo,
  getUsersByName,
  updateClientInfo,
  loadOrganization,
  deleteDepartment,
  getAllOrganization,
} from '../api/department/index';
import { message } from 'ant-design-vue';
import { TreeSelect } from 'ant-design-vue';
const SHOW_PARENT = TreeSelect.SHOW_PARENT;

const clientId = ref(''); //公司id
const id = ref(''); //公司id
const companies = ref([]); //所有公司
const clientIdStr = ref(undefined);
const userList = ref([]); // 用户清单
const isCreate = ref(false); // 是否新建
const isEditClient = ref(false); // 编辑公司
const dataSource = ref([]); // 表格部门
const drawerTitle = ref(''); //抽屉标题
const organization = ref({}); // 部门详情
const client = ref({}); // 公司详情
const editVisible = ref(false); // 抽屉开关
const organizationId = ref(''); // 所选部门ID
const clientNameStr = ref('');
const { proxy } = getCurrentInstance(); //访问this
const superiorDepartment = ref('');
const organizations = ref([]);
const oldParentId = ref('');
const oldParentName = ref('');
const fetching = ref(false);
const loading = ref(false);
onMounted(() => {
  getComponyInfo();
});

const focusUser = value => {
  userList.value = [];
  fetching.value = true;
  fetchUserList(value);
};

const fetchUser = Common.debounce(value => {
  userList.value = [];
  fetching.value = true;
  fetchUserList(value);
}, 500);

const getOrgUsers = (_, list) => {
  organization.value.managerUsers = list;
};
const getClientUsers = (_, list) => {
  client.value.managerUsers = list;
};

// 获取公司名称id
const getComponyInfo = () => {
  companies.value = [];
  getCompony().then(
    success => {
      if (success.errorCode == 0) {
        if (success.datas && success.datas.length > 0) {
          getALLClient(success.datas);
        }
      } else {
        message.error(success.errorMessage);
      }
    },
    err => {
      Common.processException(err);
    },
  );
};
// 展示子公司数据
const getALLClient = datas => {
  datas.forEach(item => {
    companies.value.push({ id: item.id, name: item.name });
    if (item.childrenClients && item.childrenClients.length > 0) {
      getALLClient(item.childrenClients);
    }
  });
};
// 编辑公司(获取公司信息)
const editClient = () => {
  if (clientNameStr.value) {
    loading.value = true;
    isEditClient.value = true;
    getClientInfo(clientId.value).then(
      success => {
        if (success.errorCode == 0) {
          client.value = success.data;
          client.value.userIds = [];
          if (
            success.data.managerUsers &&
            success.data.managerUsers.length > 0
          ) {
            userList.value = [];
            success.data.managerUsers.forEach(item =>{
              userList.value.push({text:`${item.name}(${item.no})`,id:item.id});
              client.value.userIds.push(item.id);
            });
          }
        } else {
          message.error(success.errorMessage);
        }
        loading.value = false;
      },
      error => {
        loading.value = false;
        Common.processException(error);
      },
    );
  } else {
    message.warning('请选择公司');
  }
};
// 更新公司信息
const updateClient = () => {
  const clientValue = JSON.parse(JSON.stringify(client.value));
  const { id, name, no } = clientValue;
  if (!id || !name || !no) {
    return;
  }
  updateClientInfo(clientValue).then(
    success => {
      isEditClient.value = false;
      if (success.errorCode == 0) {
        getComponyInfo();
        client.value = {};
        message.success(proxy.$t('lang.OrganizationEditPanel.describe6'));
      } else {
        message.error(success.errorMessage);
      }
    },
    err => {
      Common.processException(err);
    },
  );
};
// 获取所选公司id 名字
const getClientId = (value, client) => {
  id.value = value;
  clientId.value = value;
  clientNameStr.value = client.label;
  getOrganization();
};

// 新建部门
const createOrganization = () => {
  organization.value = {};
  organization.value.clientName = clientNameStr.value;
  organization.value.parentId = null;
  organization.value.parentName = null;
};

// 隐藏部门
const hiddenDepartment = info => {
  loading.value = true;
  $.ajax({
    url: Common.getApiURL('organizationResource/concealOrganization'),
    type: 'post',
    beforeSend: function (request) {
      Common.addTokenToRequest(request);
    },
    data: JSON.stringify(info),
    contentType: 'application/json; charset=utf-8',
    processData: false,
    success: function (data) {
      editVisible.value = false;
      loading.value = false;
      message.success(`${info.name}隐藏成功。`);
      refreshData();
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      loading.value = false;
      Common.processException(XMLHttpRequest, textStatus, errorThrown);
    },
  });
};

// 创建按钮
const createNew = organization => {
  organization.clientId = id.value;
  create(organization).then(
    success => {
      if (success.errorCode == 0) {
        message.success('新建部门成功');
        getOrganization();
        editVisible.value = false;
      } else {
        message.error(success.errorMessage);
      }
    },
    err => {
      Common.processException(err);
    },
  );
};
//刷新数据
const refreshData = () => {
  getComponyInfo();
  getOrganization();
};
// 获取所有部门
const getOrganization = () => {
  loading.value = true;
  dataSource.value = [];
  const datas = [];
  const id = clientId.value;
  getAllOrganization(id).then(
    success => {
      if (success.errorCode == 0) {
        success.datas.forEach(item => {
          datas.push(item.childrenOrganizations);
        });
        traversalTree(datas.flat(1), dataSource.value);
        clientOrganizations(dataSource.value);
      }
      loading.value = false;
      // loadAllSubClients();
    },
    err => {
      loading.value = false;
      Common.processException(err);
    },
  );
};
// 处理上级部门数据
const clientOrganizations = datas => {
  datas.forEach(item => {
    item.value = item.id;
    item.label = item.name;
    if (item.children && item.children.length > 0) {
      clientOrganizations(item.children);
    }
  });
  organizations.value = datas;
};
// 编辑部门(获取部门信息)
const editOrganization = (flag, id) => {
  organizationId.value = id;
  if (flag) {
    if (clientNameStr.value !== '') {
      editVisible.value = true;
      drawerTitle.value = '新建部门';
      createOrganization();
      fetchUserList();
      isCreate.value = true;
    } else {
      message.warning('请选择公司');
    }
  } else {
    loading.value = true;
    editVisible.value = true;
    drawerTitle.value = '编辑部门';
    loadOrganization(id).then(
      success => {
        if (success.errorCode == 0) {
          organization.value = success.data;
          organization.value.userIds = [];
          if (
            success.data.managerUsers &&
            success.data.managerUsers.length > 0
          ) {
            userList.value = [];
            success.data.managerUsers.forEach(item =>{
              userList.value.push({text:`${item.name}(${item.no})`,id:item.id});
              organization.value.userIds.push(item.id);
            });
          }
          oldParentName.value = success.data.parentName;
          oldParentId.value = success.data.parentId;
        } else {
          message.error(success.errorMessage);
        }
        loading.value = false;
      },
      err => {
        loading.value = false;
        Common.processException(err);
      },
      (isCreate.value = false),
    );
  }
};

//保存事件
const updateOrganization = () => {
  const organizationValue = JSON.parse(JSON.stringify(organization.value));
  const { clientId, name, no } = organizationValue;
  if (!clientId || !name || !no) {
    Notify.error(
      proxy.$t('lang.Notify.error'),
      proxy.$t('lang.OrganizationEditPanel.describe5'),
      true,
    );
    return;
  }
  update(organizationValue).then(
    success => {
      if (success.errorCode == 0) {
        if (success.data) {
          message.success(proxy.$t('lang.OrganizationEditPanel.describe6'));
          organization.value = {};
          getOrganization();
        }
      } else {
        message.error(success.errorMessage);
      }
      editVisible.value = false;
    },
    err => {
      Common.processException(err);
    },
  );
};

// 删除部门
const deleteOrganization = id => {
  loadOrganization(id).then(
    success => {
      const organization = success.data;
      if (organization == undefined) {
        Notify.error(
          proxy.$t('lang.Notify.error'),
          proxy.$t('lang.OrganizationEditPanel.describe4'),
          true,
        );
        return;
      }
      const params = {
        id: organization.id,
        no: organization.no,
        name: organization.name,
      };
      deleteDepartment(params).then(
        success => {
          if (success.errorCode == 0) {
            message.success(proxy.$t('lang.OrganizationEditPanel.describe3'));
            organization.value = undefined;
            getOrganization();
          } else {
            message.error(success.errorMessage);
          }
        },
        err => {
          Common.processException(err);
        },
      );
    },
    err => {
      Common.processException(err);
    },
  );
};

// 部门管理员输入的过滤条件发生改变
const fetchUserList = value => {
  const params = {
    range: {
      start: 0,
      length: 1000,
    },
    conditional: value,
  };
  getUsersByName(params).then(
    successData => {
      if (successData && successData.resultList) {
        successData.resultList.forEach(function (user) {
          if (user.no) {
            user.text = user.name + '(' + user.no + ')';
          } else {
            user.text = user.name;
          }
        });
        userList.value = successData.resultList;
      } else {
        userList.value = [];
      }
      fetching.value = false;
    },
    errorData => {
      fetching.value = false;
      Common.processException(errorData);
    },
  );

  // if (loading != null) {
  //   loading(true);
  // }
  // let searchQueryParam = {
  //   conditional: search,
  //   range: {
  //     start: 0,
  //     length: 100,
  //   },
  // };
  // getUsersByName(searchQueryParam).then(
  //   (successData) => {
  //     if (loading != null) {
  //       loading(false);
  //     }
  //     userList.value = successData.resultList;
  //   },
  //   (errorData) => {
  //     if (loading != null) {
  //       loading(false);
  //     }

  //     Common.processException(errorData);
  //   }
  // );
};

// 上级部门change事件
const parentOrganizationValueChanged = (value, label) => {
  if (!value && label.length == 0) {
    organization.value.parentId = null;
    organization.value.parentName = null;
    return;
  }
  if (organizationId.value == value) {
    message.warning('不能将自己作为上级部门！');
    organization.value.parentId = oldParentId.value;
    organization.value.parentName = oldParentName.value;
  } else {
    organization.value.parentId = value;
    organization.value.parentName = label[0];
  }
};

// 递归将childrenOrganizations赋值给children
const traversalTree = (array, target) => {
  array.map((item, index) => {
    target.push({
      id: item.id,
      no: item.no,
      key: item.id,
      children: [],
      type: item.type,
      name: item.name,
      description: item.description,
    });
    if (
      item.childrenOrganizations !== null &&
      item.childrenOrganizations.length !== 0
    ) {
      traversalTree(item.childrenOrganizations, target[index].children);
    } else {
      delete target[index].children;
    }
  });
};

// 获取所有子部门
/** 
const loadAllSubClients = () => {
  var rootClientId = null;
  for (let i = 0; i < dataSource.value.length; i++) {
    var clientOrganization = dataSource.value[i];
    if (clientOrganization.children == null) {
      rootClientId = clientOrganization.key;
    }
  }
  loadSubClients(rootClientId).then(
    success => {
      if (success.errorCode == 0) {
        if (success.datas) {
          clientAdditionHql.value = ' ct.id in (' + success.join(',') + ')';
        } else {
          clientAdditionHql.value = {
            customerDataDimensions: [
              {
                fieldName: 'ct.id',
                dataDimensionTypeNo: '202201191757',
                defaultDataDimensionTypeValueNo: '1',
              },
            ],
          };
          parentOrganizationAdditionHql.value = {
            customerDataDimensions: [
              {
                fieldName: 'organization.id',
                dataDimensionTypeNo: '202201191700',
                defaultDataDimensionTypeValueNo: '1',
              },
            ],
          };
        }
      } else {
        message.error(success.errorMessage);
      }
    },
    err => {
      Common.processException(err);
    },
  );
};*/
</script>

<style scoped>
.editable-row-operations a {
  margin-right: 8px;
}
</style>