<template>
  <div class="padding-20 page-box-row-left">
    <FormBlock :title="$t('module.resourceManage.resList')" direction="column" style="width:280px" :style="{height: treeBoxHeight}">
      <el-tree :data="baseData" :props="defaultProps" :empty-text="$t('module.resourceManage.addFunction')" highlight-current check-strictly default-expand-all indent='16' node-key="menuId" ref="menuTree" @node-click="handleNodeClick" :render-content="renderContent"  :expand-on-click-node="false" >
      </el-tree>
    </FormBlock>
    <FormBlock :title="title" direction="column">
      <PageTable ref="resourceTable" action="MenuResouceQueryList" :columns="columns" :initParam="formSearch" :autoFirst="false" style="margin-bottom: 0px;">
        <!-- <Form :model="formSearch" slot="search-bar" label-position="top" class="ivu-form-no-margin-bottom" inline>
          </Form> -->
        <Form label-position="top" class="ivu-form-no-margin-bottom" inline>
        </Form>
        <Button slot="table-bar" type="ghost" icon="plus-round" size="small" v-bind:disabled="isButtonDisabled" @click="add">{{$t('common.create')}}</Button>
        <Button slot="table-bar" type="ghost" icon="trash-a" size="small" v-bind:disabled="isButtonDisabled" @click="deleted">{{$t('common.delete')}}</Button>
      </PageTable>
    </FormBlock>
    <!-- 添加／编辑资源明细-->
    <Modal v-model="modal" width="600">
      <p slot="header">
        <span>{{ !!formInfo.btnId?$t('common.edit'):$t('common.create') }}{{$t('module.resourceManage.resource')}}</span>
      </p>
      <div>
        <Form :model="formInfo" ref="resourceForm" :rules="rules" :label-width="80">
          <Row :gutter="20" class="code-row-bg">
            <Col span="24">
            <Form-item :label="$t('module.resourceManage.resCode')" prop="btnCode">
              <Input placeholder="" v-model="formInfo.btnCode"></Input>
            </Form-item>
            </Col>
          </Row>
          <Row :gutter="20" class="code-row-bg">
            <Col span="24">
            <Form-item :label="$t('module.resourceManage.resName')" prop="btnName">
              <Input placeholder="" v-model="formInfo.btnName"></Input>
            </Form-item>
            </Col>
          </Row>
          <Row :gutter="20" class="code-row-bg">
            <Col span="24">
            <Form-item :label="$t('module.resourceManage.resAddress')" prop="url">
              <Input placeholder="" v-model="formInfo.url"></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>
<script>
import Three from "../../../tools/getThree.js";

export default {
  name: 'menu-resource',
  components: {},
  props: {},
  data() {
    const validateBtnCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this.$t('module.resourceManage.enterCode')));
      } else if (value.length > 50) {
        callback(new Error(this.$t('module.resourceManage.resCodeMaxFifty')));
      } else if (!new RegExp("^([a-zA-z0-9]|_)+$").test(value)) {
        callback(new Error(this.$t('module.resourceManage.codeContain')));
      }
      // 资源编码自动转大写
      this.formInfo.btnCode = this.formInfo.btnCode.toUpperCase();
      callback();
    };
    const validateBtnName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this.$t('module.resourceManage.enterName')));
      } else if (value != value.trim()) {
        callback(new Error(this.$t('module.resourceManage.noBlank')));
      } else if (value.length > 50) {
        callback(new Error(this.$t('module.resourceManage.resNameMaxFifty')));
      }
      callback();
    };
    const validateUrl = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this.$t('module.resourceManage.enterAdd')));
      }
      if (value != null && value != value.trim() && value.trim() === "") {
        callback(new Error(this.$t('module.resourceManage.enterLegalAdd')));
      }
      if (value != null && value.length > 100) {
        callback(new Error(this.$t('module.resourceManage.resAddMaxFifty')));
      }
      callback();
    };
    return {
      resourceTitle: this.$t('module.resourceManage.resAddresListMaxFifty'),
      menuResouceData: [],
      modal: false,
      noData: false,
      showDetail: false,
      firstLoading: true,
      formSearch: {
        menuId: ""
      },
      formInfo: {
        menuId: "",
        btnId: "",
        btnCode: "",
        btnName: "",
        url: ""
      },
      columns: [
        {
          type: "selection",
          align: "center",
          fixed: 'left',
          width: 50
        },
        {
          title: this.$t('common.operating'),
          align: "center",
          fixed: 'left',
          width: 80,
          render: (h, params) => {
            return h("RowTools", {
              props: {
                data: [
                  {
                    type: "icon",
                    icon: "md-create",
                    text: this.$t('common.edit'),
                    handle: () => {
                      this.resetForm();
                      this.formInfo = {
                        menuId: params.row.menuId,
                        btnId: params.row.btnId,
                        btnCode: params.row.btnCode,
                        btnName: params.row.btnName,
                        url: params.row.url
                      };
                      this.modal = true;
                    }
                  }
                ]
              }
            });
          }
        },
        {
          title: this.$t('module.resourceManage.resCode'),
          key: "btnCode",
          align: "center",
          ellipsis: true,
          // width: 240,
          render: (h, params) => {
            return h('span', {
              attrs: {
                title: params.row.btnCode,
                href: '#'
              }
            }, params.row.btnCode);
          }
        },
        {
          title: this.$t('module.resourceManage.resName'),
          key: "btnName",
          ellipsis: false,
          align: "center",
          // width: 240,
          render: (h, params) => {
            return h('span', {
              attrs: {
                title: params.row.btnName,
                href: '#'
              }
            }, params.row.btnName);
          }
        },
        {
          title: this.$t('module.resourceManage.resAddress'),
          key: "url",
          // width: 240,
          align: "center",
          render: (h, params) => {
            return h('span', {
              attrs: {
                title: params.row.url,
                href: '#'
              }
            }, params.row.url);
          }
        }
      ],
      rules: {
        btnCode: [
          { validator: validateBtnCode, trigger: "blur", required: true }
        ],
        btnName: [
          { validator: validateBtnName, trigger: "blur", required: true }
        ],
        url: [{ validator: validateUrl, trigger: "blur", required: true }]
      },
      baseData: [
        /* {
        orgName: this.companyName,
        orgId : '0',
        children: [],
        parentId: -1
      }*/
      ],
      selectedData: {
      },
      selectedMenuID: "",
      selectedMenuName: "",
      defaultProps: {
        children: "children",
        label: "title"
      },
      node: {},
      nodeElement: {},
      title:'',
      isButtonDisabled: true,
      treeBoxHeight: (window.innerHeight - 110) + "px"
    };
  },
  computed: {},
  computed: {},
  created: function () {
    this.$emit("setTitle", this.$t('module.resourceManage.resManage'));
    $store.dispatch("QueryMenus", {
      commonPageDTO: {
        currentPage: 1,
        pageSize: 10000
      }
    }).then(res => {
      let tree =
        new Three(res.recordList, {
          //selected: this.form.menuModuleId
        });
      this.baseData = tree.json;
    });
  },
  beforeMount: function () { },
  mounted: function () { },
  updated: function () {
    //默认显示第一个部门信息
    if (this.firstLoading && this.baseData.length > 0) {
      this.$refs["menuTree"].setCurrentKey(this.baseData[0].menuId);
      this.selectedMenuID = this.baseData[0].menuId;
      this.selectedMenuName = this.baseData[0].title;
      this.title = this.selectedMenuName; 
      this.updateResourceTitle(this.selectedMenuName);
      this.formSearch.menuId = this.baseData[0].menuId; //查询参数
      this.firstLoading = false;

      //刷新列表
      this.refresh();
    }
  },
  beforeDestroy: function () { },
  destroyed: function () { },
  beforeMount: function () { },
  mounted: function () { },
  beforeDestroy: function () { },
  destroyed: function () { },
  methods: {
    refresh() {
      //刷新列表
      this.$refs["resourceTable"].load(this.formSearch);
    },
    resetForm() {
      this.$refs["resourceForm"].resetFields();
    },
    //添加删除小图标
    renderContent(h, { node, data, store }) {
      return (
          <span title={node.label}>{node.label}</span>
      );
    },
    onOk() {
      this.$refs["resourceForm"].validate(valid => {
        if (valid) {
          if (this.formInfo.btnId) {
            this.$store
              .dispatch("MenuResouceUpdateResource", this.formInfo)
              .then(response => {
                if (response.statusCode == "0") {
                  this.$Message.success({
                    content: this.$t('module.resourceManage.editSuccess'),
                    duration: 3
                  });

                  this.modal = false; //关闭当前窗口
                  this.refresh();
                } else {
                  this.$Message.error({
                    content: response.msg,
                    duration: 3
                  });
                }
              });
          } else {
            this.$store
              .dispatch("MenuResouceAddResource", this.formInfo)
              .then(response => {
                if (response.statusCode == "0") {
                  this.$Message.success({
                    content: this.$t('module.resourceManage.createSuccess'),
                    duration: 3
                  });

                  this.modal = false; //关闭当前窗口
                  this.refresh();
                } else {
                  this.$Message.error({
                    content: response.msg,
                    duration: 3
                  });
                }
              });
          }
        } else {
          this.$Message.error({
            content: $t('common.formValidateFailed'),
            duration: 3
          });
        }
      });
    },
    updateResourceTitle(title) {
      this.resourceTitle = `${title} / ${this.$t('module.resourceManage.resList')}`;
    },
    handleNodeClick(data, node, nodeElement) {
      if(data.menuType && data.menuType == 0){
        this.isButtonDisabled = false;
        this.node = node;
        this.updateResourceTitle(data.title);
        this.formSearch.menuId = data.menuId; //查询参数
        this.selectedMenuID = data.menuId;
        //刷新列表
        this.refresh();
      }else{
        // 功能目录不能添加资源
        this.isButtonDisabled = true;
        //刷新列表
        this.$refs["resourceTable"].tableData = [];
        this.$refs["resourceTable"].total = 0;
        this.$refs["resourceTable"].param.commonPageDTO.currentPage = 1;
      }
      this.title = data.title;
    },
    add() {
      this.resetForm();
      this.formInfo.menuId = this.selectedMenuID;
      this.formInfo.btnId = "";
      this.modal = true;
    },
    deleted() {
      let deleteStr = this.getIds();
      if (deleteStr == "" || deleteStr == undefined) {
        this.$Message.warning({
          content: this.$t('module.resourceManage.selectDeletion'),
          duration: 3
        });
        return;
      }
      new $confirm(this.$t('module.resourceManage.confirmDelete'), this).then(() => {
        this.$store.dispatch("MenuResouceDeleteResource", { btnIds: deleteStr }).then(response => {
          if (response.statusCode == "0") {
            this.refresh();
          } else {
            this.$Message.warning({
              content: response.msg,
              duration: 3
            });
          }
        });
      });
    },
    getIds() {
      let list = this.$refs["resourceTable"].getSelectioned() || [];
      let ids = [];
      for (let u of list) {
        ids.push(u.btnId);
      }
      return ids.join(",");
    }
  },
  watch: {},
  directives: {}
};
</script>
