<template>
  <div>
    <PageTable ref="sysGroupTable" action="SysGroupMgQueryGroupMemberList" :columns="columns" :initParam="formSearch" :autoFirst="true">
      <Form :model="formSearch" ref="formSearch" slot="search-bar" label-position="top" class="ivu-form-no-margin-bottom" inline>
        <Form-item prop="userName" :label="$t('module.groupManage.username')">
          <Input type="text" v-model="formSearch.userName" :placeholder="$t('module.groupManage.enterUsername')"></Input>
        </Form-item>
        <Form-item prop="userCode" :label="$t('module.groupManage.userAccount')">
          <Input type="text" v-model="formSearch.userCode" :placeholder="$t('module.groupManage.enterAccount')"></Input>
        </Form-item>
      </Form>
      <div slot="handle-bar">
        <Button size="small" @click.native="refresh" type="warning" icon="ios-search">{{$t('common.search')}}</Button>
        <Button size="small" @click.native="reset" type="info" icon="md-sync">{{$t('common.reset')}}</Button>
      </div>
      <div slot="table-bar">
        <Button type="ghost" icon="plus-round" size="small" @click="add">{{$t('common.create')}}</Button>
        <Button type="ghost" icon="trash-a" size="small" @click="deleted">{{$t('common.delete')}}</Button>
      </div>
    </PageTable>

    <Modal v-model="modal" width="820">
      <PersonSelectWin @ok="addUser" @oncancle="oncancle"></PersonSelectWin>
      <div slot="footer"></div>
    </Modal>
  </div>
</template>

<script>

import PersonSelectWin from "../../../components/OrgPersonSelectWin.vue";
export default {
  components: {
    PersonSelectWin
  },
  props: {
    groupId: '',
    groupName: '',
  },
  data() {

    return {
      modal: false,
      winTitle: "",
      formSearch: {
        groupId: this.groupId,
        userName: '',
        userCode: '',
      },
      formInfo: {
        groupId: this.groupId,
        userName: '',
        userId: '',
        userCode: '',
        version: '',

      },
      columns: [
        {
          type: "selection",
          width: 60,
          align: "center"
        },
        {
          title: this.$t('module.groupManage.username'),
          key: "userName"
        },
        {
          title: this.$t('module.groupManage.userAccount'),
          key: "userCode"
        },
        {
          title: this.$t('module.groupManage.affiliation'),
          key: "orgName"
        },
      ],
    };
  },
  methods: {
    addUser(selectUserList) {
      let groupMemberList = [];
      selectUserList.map((res) => {
        groupMemberList.push({
          orgId: res.value.orgIds,
          userId: res.value.userId
        })
      })
      $store.dispatch('SysGroupMgSaveGroup', {
        groupId: this.groupId,
        groupMemberList
      }).then((res) => {
        if (!res.success) {
          this.$Message.warning({
            content: res.msg,
            duration: 2
          });
          return;
        }
        this.$Message.success({
          content: $t('module.groupManage.addSuccess')
        });
        this.refresh();
      })
      this.modal = false;
    },
    oncancle(){
      this.modal = false;
    },
    reset() {
      this.$refs["formSearch"].resetFields();
      this.refresh();
    },
    refresh() {
      //刷新列表
      this.$refs["sysGroupTable"].load(this.formSearch);
    },
    loadNode(node, resolve) {
      let checked = node.checked;
      node.checked = false; //每次加载，均取消当前功能的复选框选中状态
      this.node = node;
      //
      if (node.level == 0) {
        resolve(this.baseData);
        return;
      }
      let parentId = 0;
      if (node.level != 0) {
        parentId = node.data.orgId;
      }

      $store
        .dispatch("OrgMgQueryOrgListByCompanyId", {
          companyId: '2039EA839D3841129D0EFDDDB03575BF',
          parentId: parentId,
          sortDTO: {
            fieldName: "",
            orderBy: ""
          }
        })
        .then(res => {
          if (res.statusCode != 0) {
            this.$Message.warning({
              content: res.msg,
              duration: 3
            });
            return;
          }
          resolve(res.dataResult);
        });
    },
    onOk() {
      this.$refs["sysGroupForm"].validate(valid => {
        if (valid) {
          if (this.effectDate.length == 2) {
            this.formInfo.groupEffectBegin = this.effectDate[0];
            this.formInfo.groupEffectEnd = this.effectDate[1];
          }

          if (this.formInfo.groupId) {
            this.$store
              .dispatch("SysGroupMgUpdateGroup", this.formInfo)
              .then(response => {
                if (response.statusCode == "0") {
                  this.$Message.success({
                    content:  this.$t('module.groupManage.editGroupSuccess'),
                    duration: 3
                  });

                  this.modal = false; //关闭当前窗口
                  this.refresh();
                } else {
                  this.$Message.error({
                    content: response.msg,
                    duration: 3
                  });
                }
              });
          } else {
            this.$store
              .dispatch("SysGroupMgSaveGroup", this.formInfo)
              .then(response => {
                if (response.statusCode == "0") {
                  this.$Message.success({
                    content: this.$t('module.groupManage.addGroupSuccess'),
                    duration: 3
                  });
                  this.modal = false; //关闭当前窗口
                  this.refresh();
                } else {
                  this.$Message.error({
                    content: response.msg,
                    duration: 3
                  });
                }
              });
          }
        } else {
          this.$Message.error({
            content: this.$t('common.formValidateFailed'),
            duration: 3
          });
        }
      });
    },
    handleNodeClick(data, node, nodeElement) {
      this.node = node;

      if (data.orgId == '0') {
        this.formSearch.orgId = '';
      } else {
        this.formSearch.orgId = data.orgId; //查询参数
      }
      //刷新列表
      this.refresh();
    },
    add() {
      this.winTitle = this.$t('module.groupManage.addGroup');
      this.modal = true;
    },
    deleted() {
      let deleteStr = this.getIds();
      if (deleteStr == "" || deleteStr == undefined) {
        this.$Message.warning({
          content:this.$t('module.groupManage.selectItems'),
          duration: 3
        });
        return;
      }
      new $confirm(this.$t('module.groupManage.confirmDeletion'), this).then(() => {
        $store
          .dispatch("SysGroupMgDeleteGroupMember", {
            groupMemberIds: deleteStr,
            // groupId: this.groupId
          })
          .then(response => {
            if (response.statusCode != 0) {
              this.$Message.warning({
                content: response.msg,
                duration: 3
              });
              return;
            }
            this.$Message.warning({
              content: this.$t('module.groupManage.deleteSuccess'),
              duration: 3
            });

            this.refresh();
          });
      });
    },
    getIds() {
      let list = this.$refs["sysGroupTable"].getSelectioned() || [];
      let ids = [];
      for (let u of list) {
        ids.push(u.groupMemberId);
      }
      return ids.join(",");
    },
    changeEffectDate(value) {
      if (value && value.length > 0 && value[0] == "") {
        this.initEffectDate();
      } else {
        this.effectDate = value;
      }
    },
    initEffectDate() {
      //默认从当天开始，有效期至50年后
      let currentDate = new Date();
      let effectBeginStr = currentDate.Format("yyyy-MM-dd");

      let effectEndDate = new Date(currentDate);
      effectEndDate.setFullYear(currentDate.getFullYear() + 50);

      let effectEndStr = effectEndDate.Format("yyyy-MM-dd");

      this.effectDate = [effectBeginStr, effectEndStr];
    },
    jsonObjectCopy(target, source) {
      //只拷贝target中存在的key
      let targetKeys = Object.keys(target);
      for (const key in targetKeys) {
        if (source.hasOwnProperty(targetKeys[key])) {
          target[targetKeys[key]] = source[targetKeys[key]];
        }
      }
    },
    initFormInfo() {
      this.formInfo = {
        orgId: '',
        groupId: '',
        groupName: '',
        orgId: '',
        orgName: '',
        description: '',
        groupEffectBegin: '',
        groupEffectEnd: '',
        version: '',

      };
    },
  },
};
</script>
<style lang="less">

</style>
