<template>
  <div class="no-border-collapse-page">
    <Collapse class="mg-t10" v-model="collapseBase">
      <Panel name="1" :isActive="true">
        {{ this.$t("module.role.basicInfo") }}
        <div slot="content">
          <Form :model="formInfo" ref="formRole" class="ivu-form-no-margin-bottom" :rules="rule" label-width="90">
            <Row :gutter="20" class="code-row-bg">
              <Col span="12" style="border:none;">
                <Form-item prop="orgName" :label="$t('module.userManage.affiliation')">
                  <Input placeholder="" size="small" v-model="formInfo.orgName" maxlength="30" style="width:90%"
                         disabled></Input>
                </Form-item>
              </Col>
              <Col span="12">
                <Form-item prop="templateId" :label="$t('module.role.menuTem')">
                  <Select size="small" v-model="formInfo.templateId" @on-change="onTemplateChange"
                          style="min-width:auto;width:90%;" clearable>
                    <Option v-for="item in templateList" :title="item.templateName" :value="item.templateId"
                            :key="item.templateId">{{ item.templateName }}
                    </Option>
                  </Select>
                </Form-item>
              </Col>
            </Row>
            <Row :gutter="20" class="code-row-bg">
              <Col span="12" style="border:none;">
                <Form-item prop="roleName" :label="$t('module.role.roleName')">
                  <Input placeholder="" size="small" v-model="formInfo.roleName" maxlength="50"
                         style="width:90%"></Input>
                </Form-item>
              </Col>
              <Col span="12" style="border:none;">
                <Form-item prop="roleCode" :label="$t('module.role.roleCode')">
                  <Input placeholder="" size="small" v-model="formInfo.roleCode" maxlength="50"
                         style="width:90%"></Input>
                </Form-item>
              </Col>
            </Row>
            <Form-item prop="effectBegin" :label="$t('module.role.effectBegin')">
              <Row>
                <Col span="10" style="padding-left:0">
                  <DatePicker type="date" ref="effectBegin" transfer="true" :placeholder="$t('module.role.selectDate')"
                              style="width: 200px;height:24px;" :value="formInfo.effectBegin" size="small"
                              @on-change="changeEffectBegin" @on-clear="clearEffectBegin"></DatePicker>
                </Col>
                <Col span="2" style="text-align:center;padding-left:0px;">{{ $t("module.role.to") }}
                </Col>
                <Col span="9">
                  <DatePicker type="date" ref="effectEnd" transfer="true" :placeholder="$t('module.role.selectDate')"
                              style="width: 200px;height:24px;" :value="formInfo.effectEnd" size="small"
                              @on-change="changeEffectEnd" @on-clear="clearEffectEnd"></DatePicker>
                </Col>
              </Row>
            </Form-item>
            <Form-item :label="$t('common.remark')">
              <Input placeholder="" type="textarea" :rows="1" size="small" v-model="formInfo.remark" maxlength="100"
                     style="width:90%"></Input>
            </Form-item>
          </Form>
        </div>
      </Panel>
    </Collapse>
    <Collapse class="mg-t10" v-model="collapseList">
      <Panel name="1" :isActive="true">
        {{ $t("module.role.functionPermissionList") }}
        <div slot="content">
          <!-- <p slot="header">
            <span>功能权限列表</span>
          </p> -->
          <div style="height: 400px;overflow-y: auto;overflow-x: hidden">
            <el-tree :data="baseData" :show-checkbox="true" ref="menuTree" :props="treeProps"
                     node-key="menuId"></el-tree>
          </div>
          <Spin size="large" fix v-if="isQueryMenusAndBtns"></Spin>
        </div>
      </Panel>
    </Collapse>
    <Collapse class="mg-t10" v-model="collapsehistory">
      <Panel name="1" :isActive="true">
        {{ $t("module.userManage.historyRecord") }}
        <div slot="content">
          <PageTable ref="logTable" action="QueryUserLogList" :initParam="initParams" :columnsFn="columnsLog"
                     :isPageLeft="false"
                     :isSearch="false" :isTableHeight="false"></PageTable>
        </div>
      </Panel>
    </Collapse>
  </div>
</template>
<script>
import Three from "../../../tools/getThree.js";
import OperateLogDetail from "../logQuery/OperateLogDetail.vue";

export default {
  name: "RoleEdit",
  components: {},
  props: {
    roleId: {
      type: String,
      default() {
        return "";
      }
    },
    version: {
      type: String,
      default() {
        return "";
      }
    },
    orgId: {
      type: String,
      default() {
        return "";
      }
    },
    orgName: {
      type: String,
      default() {
        return "";
      }
    }
  },
  data() {
    const validateRoleCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this.$t("module.role.warning.enterRoleCode")));
      } else if (value.length > 50) {
        callback(new Error(this.$t("module.role.warning.maxFifty")));
      } else if (!new RegExp("^([a-zA-z0-9]|_)+$").test(value)) {
        callback(new Error(this.$t("module.role.warning.codeFormat")));
      }
      callback();
    };
    return {
      collapseBase: 1,
      collapseList: 1,
      collapsehistory: 1,
      formInfo: {
        orgId: "",
        orgName: "",
        roleName: "",
        remark: "",
        roleId: "",
        menuIds: "",
        effectBegin: "",
        effectEnd: "",
        roleCode: "",
        templateId: ""
      },
      initParams: {
        recordType: "ROLE",
        recordId: this.roleId
      },
      rule: {
        roleName: [{ required: true, message: this.$t("module.role.warning.enterRoleName"), trigger: "blur" }],
        roleCode: [
          { validator: validateRoleCode, trigger: "blur", required: true }
        ]
      },
      templateList: [],
      baseData: [],
      eventList: [],
      treeProps: {
        label: "title",
        children: "children"
      },
      isQueryMenusAndBtns: false
    };
  },
  computed: {},
  created: function() {
    if (this.roleId) {
      this.$emit("SetTitle", this.$t("module.role.editRole"));
    } else {
      this.$emit("SetTitle", this.$t("module.role.createRole"));
    }
    this.$emit("SetPageActions", [
      {
        text: this.$t("common.confirm"),
        theme: "primary",
        icon: "md-create",
        handle: () => {
          this.saveOrUpdateRole();
        }
      }
    ]);
    $store.dispatch("GetValueSetByCode", { code: "EVENT" }).then(response => {
      this.eventList = response.dataResult;
    });
    // this.queryRole();
  },
  beforeMount: function() {

  },
  mounted: function() {
    this.init();
    this.$refs.logTable.tableH = 300;
  },
  beforeDestroy: function() {

  },
  destroyed: function() {

  },
  methods: {
    init() {
      if (this.roleId) {
        $store.dispatch("GetRoleDetail", { id: this.roleId }).then(response => {
          let selectMenus = response.menus,
            menuIds = [];
          for (let item of selectMenus) {
            menuIds.push(item.menuId);
          }
          menuIds = menuIds.join(",");

          this.formInfo = {
            orgId: response.orgId,
            orgName: response.orgName,
            roleName: response.roleName,
            remark: response.remark,
            roleId: response.roleId,
            menuIds: menuIds,
            effectBegin: this.getDateString(response.effectBegin),
            effectEnd: this.getDateString(response.effectEnd),
            roleCode: response.roleCode,
            templateId: response.menuTemplateId,
            version: this.version
          };
          // 显示功能及资源权限
          if (!this.formInfo.templateId) {
            this.onTemplateChange();
          }
        });
      } else {
        // 默认有效期
        var date = new Date();
        var month = date.getMonth() + 1;
        var currentDate = date.getFullYear() + "-" + month + "-" + date.getDate();
        var endDate = date.getFullYear() + 50 + "-" + month + "-" + date.getDate();

        this.formInfo.orgId = this.orgId;
        this.formInfo.orgName = this.orgName;
        this.formInfo.effectBegin = currentDate;
        this.formInfo.effectEnd = endDate;
        // 显示功能及资源权限
        this.onTemplateChange();
      }
      // 初始化模板下拉框
      $store.dispatch("QueryTemplateList", {}).then(res => {
        this.templateList = res;
      });
    },
    saveOrUpdateRole() {
      this.$refs["formRole"].validate(valid => {
        if (valid) {
          // 未选择菜单模板，保存权限信息
          if (!this.formInfo.templateId) {
            let menusList = this.$refs["menuTree"].getCheckedNodes();
            var menuIds = [];
            var btnIds = [];
            for (let item of menusList) {
              if (!!item.btnCode) {
                btnIds.push(item.menuId);
                menuIds.push(item.menuModuleId);
              } else {
                menuIds.push(item.menuId);
              }
            }
            menuIds = menuIds.join(",");
            btnIds = btnIds.join(",");
          }
          if (this.formInfo.roleId) {
            let param = {
              roleId: this.formInfo.roleId,
              remark: this.formInfo.remark,
              orgId: this.formInfo.orgId,
              orgName: this.formInfo.orgName,
              roleName: this.formInfo.roleName,
              roleType: 0,
              version: this.formInfo.version,
              effectBegin: this.getDateString(this.formInfo.effectBegin),
              effectEnd: this.getDateString(this.formInfo.effectEnd),
              roleCode: this.formInfo.roleCode,
              menuTemplateId: this.formInfo.templateId,
              menuIds: menuIds,
              btnIds: btnIds
            };
            $store.dispatch("UpdateRole", param).then(response => {
              if (response.statusCode == "0") {
                this.$Message.success({
                  content: this.$t("module.role.warning.updateSuccessfully"),
                  duration: 3
                });
                this.$emit("Close");
              } else {
                this.$Message.warning({
                  content: response.msg,
                  duration: 3
                });
              }
            });
          } else {
            let param = {
              remark: this.formInfo.remark,
              orgId: this.formInfo.orgId,
              orgName: this.formInfo.orgName,
              roleName: this.formInfo.roleName,
              roleType: 0,
              effectBegin: this.getDateString(this.formInfo.effectBegin),
              effectEnd: this.getDateString(this.formInfo.effectEnd),
              roleCode: this.formInfo.roleCode,
              menuTemplateId: this.formInfo.templateId,
              menuIds: menuIds,
              btnIds: btnIds
            };
            $store.dispatch("AddRole", param).then(response => {
              if (response.statusCode == "0") {
                this.$Message.success({
                  content: this.$t("module.role.warning.createRoleSuccessfully"),
                  duration: 3
                });
                this.$emit("Close");
              } else {
                this.$Message.warning({
                  content: response.msg,
                  duration: 3
                });
              }
            });
          }
          // this.$emit("close");
        } else {
          this.$Message.error({
            content: this.$t("module.valueSet.warning.formValidateFailed"),
            duration: 3
          });
          return 0;
        }
      });
    },
    changeEffectBegin(date) {
      if (this.formInfo.effectEnd && date && new Date(date) > new Date(this.formInfo.effectEnd)) {
        this.formInfo.effectBegin = "";
        this.$refs["effectBegin"].handleClear();
        this.$Message.warning({
          content: this.$t("module.valueSet.warning.dateCompare")
        });
        return;
      }

      this.formInfo.effectBegin = date;
    },
    clearEffectBegin() {
      this.formInfo.effectBegin = "";
    },
    changeEffectEnd(date) {
      if (
        this.formInfo.effectBegin &&
        date &&
        new Date(date) < new Date(this.formInfo.effectBegin)
      ) {
        this.formInfo.effectEnd = "";
        this.$refs["effectEnd"].handleClear();
        this.$Message.warning({
          content: this.$t("module.valueSet.warning.dateCompare")
        });
        return;
      }

      this.formInfo.effectEnd = date;
    },
    clearEffectEnd() {
      this.formInfo.effectEnd = "";
    },
    getDateString(DateStr) {
      if (
        DateStr == undefined ||
        DateStr == null ||
        DateStr == "" ||
        DateStr.trim() == ""
      ) {
        return "";
      }
      // return DateStr.split(" ")[0];
      let dateList = DateStr.split(" ")[0].split("-");
      let newDateList = [];
      let newItem = "";
      for (let key = 0; key < dateList.length; key++) {
        let newNummber = parseInt(dateList[key]);
        if (newNummber < 10) {
          newNummber = "0" + newNummber;
        }
        newDateList.push(newNummber);

      }
      ;
      return newDateList.join("-");
    },
    onTemplateChange(id) {
      if (id) {
        //根据菜单模板显示功能及资源权限
        this.isQueryMenusAndBtns = true;
        $store.dispatch("GetMenuTree", { templateId: id }).then(response => {
          this.isQueryMenusAndBtns = false;
          for (const key in response.data) {
            let element = response.data[key];
            element.disabled = true;
          }
          this.baseData = new Three(response.data).json;
          this.$refs["menuTree"].setCheckedKeys(response.checkList);
        });
      } else {
        //根据角色模板显示功能及资源权限
        this.isQueryMenusAndBtns = true;
        $store.dispatch("QueryMenusAndBtns", {
          commonPageDTO: {
            currentPage: 1,
            pageSize: 10000
          },
          roleId: this.formInfo.roleId
        }).then(response => {
          this.isQueryMenusAndBtns = false;
          this.baseData = new Three(response.data).json;
          this.$refs["menuTree"].setCheckedKeys(response.menuIdList);
        });
      }
    },
    columnsLog() {
      return [
        {
          title: this.$t("common.operating"),
          align: "center",
          width: 80,
          render: (h, params) => {
            return h("RowTools", {
              props: {
                data: [
                  {
                    type: "button",
                    text: this.$t("module.logQuery.detail"),
                    handle: () => {
                      new this.$sidelipPage(OperateLogDetail, {
                        props: {
                          logId: params.row.id
                        }
                      });
                    }
                  }
                ]
              }
            });
          }
        },
        {
          title: this.$t("module.logQuery.event"),
          key: "event",
          align: "center",
          width: 150,
          render: (h, params) => {
            return h(
              "span",
              {
                attrs: {
                  title: this.getEventName(params.row.event)
                }
              },
              this.getEventName(params.row.event)
            );
          }
        },
        {
          title: this.$t("module.logQuery.createdTime"),
          key: "timestamp",
          align: "center",
          width: 130,
          ellipsis: true,
          render: (h, params) => {
            return h(
              "span",
              {
                attrs: {
                  title: params.row.timestamp
                }
              },
              params.row.timestamp
            );
          }
        },
        {
          title: this.$t("module.logQuery.userId"),
          key: "userId",
          width: 120,
          align: "center",
          render: (h, params) => {
            return h(
              "span",
              {
                attrs: {
                  title: params.row.userId
                }
              },
              params.row.userId
            );
          }
        },
        {
          title: this.$t("module.logQuery.userName"),
          key: "userName",
          align: "center",
          width: 120,
          render: (h, params) => {
            return h(
              "span",
              {
                attrs: {
                  title: params.row.userName
                }
              },
              params.row.userName
            );
          }
        },
        {
          title: this.$t("module.logQuery.userIp"),
          key: "userIP",
          align: "center",
          width: 180,
          render: (h, params) => {
            return h(
              "span",
              {
                attrs: {
                  title: params.row.userIP
                }
              },
              params.row.userIP
            );
          }
        },
        {
          title: this.$t("module.logQuery.extra"),
          key: "extra",
          align: "center",
          width: 180,
          ellipsis: true,
          render: (h, params) => {
            return h(
              "span",
              {
                attrs: {
                  title: params.row.extra
                }
              },
              params.row.extra
            );
          }
        }
      ];
    },
    getEventName(event) {
      for (let item of this.eventList) {
        if (event == item.vsiKey) {
          return item.vsiValue;
        }
      }
    }
  },
  watch: {},
  directives: {}
};
</script>
<style lang="less">
</style>
