<template>
  <div class="padding-20">
    <FormBlock :title="$t('module.groupManage.groupList')" direction="column" style="width:300px;float:left"  :style="{height: treeBoxHeight}">
      <el-tree :data="baseData" :props="defaultProps" :load="loadNode" highlight-current check-strictly lazy indent="20" default-expanded-keys="[0]" node-key="orgId" ref="orgTree" @node-click="handleNodeClick" :render-content="renderContent" :expand-on-click-node="false">
      </el-tree>
    </FormBlock>
    <div style="overflow: hidden" class="run-mod-box form-block">
      <PageTable ref="sysGroupTable" action="SysGroupMgQueryGropListByOrgId" :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="groupName" :label="$t('module.groupManage.groupName')">
            <Input type="text" maxlength="30" size="small" v-model="formSearch.groupName" placeholder="请输入群组名称" ></Input>
          </Form-item>
        </Form>
        <div slot="handle-bar">
          <Button size="small" v-bind:disabled="isButtonDisabled" @click.native="refresh" type="warning" icon="ios-search">{{$t('common.search')}}</Button>
          <Button size="small" v-bind:disabled="isButtonDisabled" @click.native="reset" type="info" icon="md-sync">{{$t('common.reset')}}</Button>
        </div>
        <div slot="table-bar">
          <Button type="ghost" v-bind:disabled="isButtonDisabled" icon="plus-round" size="small" @click="add">{{$t('common.create')}}</Button>
          <Button type="ghost" v-bind:disabled="isButtonDisabled" icon="trash-a" size="small" @click="deleted">{{$t('common.delete')}}</Button>
        </div>

      </PageTable>
    </div>
    <!-- 添加／编辑群组明细-->
    <Modal v-model="modal" width="600">
      <p slot="header">
        <span>{{ winTitle }}</span>
      </p>
      <div>
        <Form :model="formInfo" ref="sysGroupForm" :rules="rules" :label-width="80">
          <Row :gutter="20" class="code-row-bg">
            <Col span="24">
            <Form-item :label="$t('module.groupManage.groupName')" prop="groupName">
              <Input placeholder="" v-model="formInfo.groupName"></Input>
            </Form-item>
            </Col>
          </Row>
          <Row :gutter="20" class="code-row-bg">
            <Col span="24">
            <Form-item :label="$t('module.groupManage.groupCode')" prop="groupCode">
              <Input placeholder="" v-model="formInfo.groupCode"></Input>
            </Form-item>
            </Col>
          </Row>
          <Row :gutter="20" class="code-row-bg">
            <Col span="24">
            <Form-item prop="effectDate" :label="$t('module.groupManage.validity')">
              <DatePicker :value="effectDate" format="yyyy/MM/dd" type="daterange" placement="bottom-end" placeholder="Select date" style="width:100%;" v-bind:readonly="canNotBeEdit" @on-change="changeEffectDate"></DatePicker>
            </Form-item>
            </Col>
          </Row>
          <Row :gutter="20" class="code-row-bg">
            <Col span="24">
            <Form-item :label="$t('module.groupManage.affiliation')" prop="orgName">
              <Input placeholder=""  v-model="formInfo.orgName"></Input>
            </Form-item>
            </Col>
          </Row>

          <Row :gutter="20" class="code-row-bg">
            <Col span="24">
            <Form-item :label="$t('module.groupManage.groupDesc')" prop="description">
              <Input placeholder="" v-model="formInfo.description"></Input>
            </Form-item>
            </Col>
          </Row>

        </Form>
      </div>
      <div slot="footer" class="run-modal-ftbButton">
        <Button type="primary" @click="onOk()">{{$t('common.confirm')}}</Button>
      </div>

    </Modal>
  </div>
</template>
<style lang="less">

</style>
<script>
import Three from "../../../tools/getThree.js";
import SysGroupMemberPage from "./SysGroupMemberManage.vue";


export default {
  name: 'sys-group-manage',
  components: {

  },
  props: {},
  data() {
    const validateGroupCode = (rule, value, callback) => {
      if (value == null || value === "") {
        callback(new Error(this.$t('module.groupManage.enterCode')));
      } else if (value.length > 50) {
        callback(new Error(this.$t('module.groupManage.codeMaxFifty')));
      } else if (!new RegExp("^[a-zA-z0-9]+$").test(value)) {
        callback(new Error(this.$t('module.groupManage.codeFormat')));
      }
      callback();
    };
    const validateGroupName = (rule, value, callback) => {
      if (value == null || value === "") {
        callback(new Error(this.$t('module.groupManage.enterName')));
      } else if (value != value.trim()) {
        callback(new Error(this.$t('module.groupManage.noBlank')));
      } else if (value.length > 50) {
        callback(new Error(this.$t('module.groupManage.nameMaxFifty')));
      }
      callback();
    };
    const validateDesc = (rule, value, callback) => {
      if (value != null && value != value.trim() && value.trim() === "") {
        callback(new Error(this.$t('module.groupManage.enterCorrectDesc')));
      }
      if (value != null && value.length > 100) {
        callback(new Error(this.$t('module.groupManage.descMaxOH')));
      }
      callback();
    };
    return {
      menuResouceData: [],
      modal: false,
      winTitle: "",
      noData: false,
      showDetail: false,
      firstLoading: true,
      // effectDate: ['2017/12/04', '2067/12/04'],
      effectDate: [],
      formSearch: {
        orgId: '',
        groupId: '',
        groupName: ''
      },
      formInfo: {
        orgId: '',
        groupId: '',
        groupName: '',
        orgId: '',
        orgName: '',
        description: '',
        groupEffectBegin: '',
        groupEffectEnd: '',
        version: '',

      },
      columns: [
        {
          fixed: 'left',
          type: "selection",
          width: 50,
          align: "center"
        },
        {
          fixed: 'left',
          title: this.$t('common.operating'),
          align: "center",
          width: 120,
          render: (h, params) => {
            return h("RowTools", {
              props: {
                data: [
                  {
                    type: "icon",
                    icon: "md-create",
                    text: this.$t('common.edit'),
                    handle: () => {
                      this.resetForm();
                      this.winTitle = this.$t('module.groupManage.editGroup');
                      this.modal = true;
                      this.$nextTick(function() {
                        this.jsonObjectCopy(this.formInfo, params.row);
                        let startDate = this.formInfo.groupEffectBegin;
                        let endDate = this.formInfo.groupEffectEnd;

                        if(startDate && startDate.split(' ').length == 2) {
                          this.formInfo.groupEffectBegin = startDate.split(' ')[0];
                        }
                        if(endDate && endDate.split(' ').length == 2) {
                          this.formInfo.groupEffectEnd = endDate.split(' ')[0];
                        }

                        this.effectDate = [this.formInfo.groupEffectBegin, this.formInfo.groupEffectEnd];
                      });
                    }
                  },
                  {
                    type: "button",
                    text: this.$t('module.groupManage.memberManage'),
                    handle: () => {
                      new this.$sidelipPage(SysGroupMemberPage, {
                        props: {
                          groupId: params.row.groupId,
                          groupName: params.row.groupName,
                        }
                      });
                    }
                  }
                ]
              }
            });
          }
        },
        {
          title: this.$t('module.groupManage.groupName'),
          width: 120,
          align: 'center',
          render: (h, params) => {
            return h('div', {
              attrs: {
                class: 'ivu-table-cell ivu-table-cell-ellipsis',
                title: params.row.groupName
              }
            }, params.row.groupName);
          }
        },
        {
          title: this.$t('module.groupManage.groupCode'),
          width: 120,
          align: 'center',
          render: (h, params) => {
            return h('div', {
              attrs: {
                class: 'ivu-table-cell ivu-table-cell-ellipsis',
                title: params.row.groupCode
              }
            }, params.row.groupCode);
          }
        },
        {
          title: this.$t('module.groupManage.affiliation'),
          width: 120,
          align: 'center',
          render: (h, params) => {
            return h('div', {
              attrs: {
                class: 'ivu-table-cell ivu-table-cell-ellipsis',
                title: params.row.orgName
              }
            }, params.row.orgName);
          }
        },
        {
          title: this.$t('module.groupManage.validity'),
          width: 120,
          align: 'center',
          render: (h, params) => {
            let startDate = (params.row.groupEffectBegin ) ? params.row.groupEffectBegin: '2000-01-01';
            let endDate = (params.row.groupEffectEnd) ? params.row.groupEffectEnd : '2099-12-31';
            return h('div', {}, startDate+ this.$t('module.groupManage.to') +endDate);
          }
        },
        {
          title: this.$t('module.groupManage.groupDesc'),
          width: 120,
          align: 'center',
          render: (h, params) => {
            return h('div', {
              attrs: {
                class: 'ivu-table-cell ivu-table-cell-ellipsis',
                title: params.row.description
              }
            }, params.row.description);
          }
        }
      ],
      rules: {
        groupCode: [
          { validator: validateGroupCode, trigger: "blur", required: true }
        ],
        groupName: [
          { validator: validateGroupName, trigger: "blur", required: true }
        ],
        description: [{ validator: validateDesc, trigger: "blur" }]
      },
      baseData: [],
      selectedData: {
      },
      selectedMenuID: "",
      selectedMenuName: "",
      defaultProps: {
        children: "children",
        label: "orgName"
      },
      node: {},
      nodeElement: {},
      isButtonDisabled: true,
      treeBoxHeight: (window.innerHeight - 110) + "px"
    };
  },
  methods: {
    reset() {
      this.$refs["formSearch"].resetFields();
      this.refresh();
    },
    refresh() {
      //刷新列表
      this.$refs["sysGroupTable"].load(this.formSearch);
    },
    resetForm() {
      this.$refs["sysGroupForm"].resetFields();
    },
    loadNode(node, resolve) {
      let checked = node.checked;
      node.checked = false; //每次加载，均取消当前功能的复选框选中状态
      this.node = node;

      $store
        .dispatch("QueryOrgListByCompanyId", {
          "orgId": node.data.orgId 
        })
        .then(res => {
          if (res.statusCode != 0) {
            this.$Message.warning({
              content: res.msg,
              duration: 3
            });
            return;
          }
          resolve(res.dataResult.depList);
        });
    },
    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("SysGroupMgAddGroup", 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(1 == this.$refs["orgTree"].getCurrentNode().checked){
        this.isButtonDisabled = false;
        if (data.orgId == '0') {
          this.formSearch.orgId = '';
        } else {
          this.formSearch.orgId = data.orgId; //查询参数
        }
        //刷新列表
        this.refresh();
      }else{
        this.isButtonDisabled = true;
        //刷新列表
        this.$refs["sysGroupTable"].tableData = [];
        this.$refs["sysGroupTable"].total = 0;
        this.$refs["sysGroupTable"].param.commonPageDTO.currentPage = 1;
      }
    },
    add() {
      this.resetForm();
      this.initFormInfo();
      this.winTitle = this.$t('module.groupManage.addGroup');
      if (!this.node || this.node.data.orgId == '0') {
        this.$Message.warning({
          content: this.$t('module.groupManage.hint')
        });
        return;
      }
      this.initEffectDate();
      this.formInfo.orgId = this.node.data.orgId;
      this.formInfo.orgName = this.node.data.orgName;
      this.modal = true;
    },
    deleted() {
      let deleteStr = this.getIds();
      if (deleteStr == "" || deleteStr == undefined) {
        this.$Message.warning({
          content: this.$t('module.groupManage.selectItems'),
          duration: 3
        });
        return;
      }
      console.log(deleteStr);
      new $confirm(this.$t('module.groupManage.confirmDeletion'), this).then(() => {
        this.$store
          .dispatch("SysGroupMgDeleteGroup", {
            groupIds: deleteStr
          })
          .then(response => {
            if (response.statusCode != 0) {
              this.$Message.warning({
                content: response.msg,
                duration: 3
              });
              return;
            }
            this.$Message.success({
              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.groupId);
      }
      return ids.join(",");
    },
    changeEffectDate(value) {

      console.log(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>
