import * as API from 'api/base/permissions';
import {
  isIntNum
} from 'validate';

export default {
  name: 'Permissions',
  components: {
    UiEdit: resolve => require(['views/system/permissions/edit'], resolve)
  },
  data() {
    return {
      loading: false,
      id: '', // 权限id(编辑的时候使用)
      params: {
        type: 0,
        parent_id: '',
        name: '',
        title: '',
        description: '',
        path: '',
        icon: '',
        status: 1,
        displayorder: 0,
        open: 0, // 打开方式: 0:iframe方式 1打开新窗口 2:弹出窗口 3:vue组件
        height: 0,
        width: 0
      },
      tree: [],
      iconObj: {
        show: false,
        type: ''
      },
      editObj: {
        show: false,
        data: null
      },
      checked: [], // 复选框勾选项
      window: {
        min: 0
      }
    };
  },
  created() {
    this.index();
  },
  watch: {
    'params.open'(value) {
      if (value == 2) {
        this.window.min = 100;
      } else {
        this.window.min = 0;
      }
    }
  },
  methods: {
    index() {
      this.isShowLoading(false);
      API.index().then(res => {
        this.isShowLoading(false);
        if (res.code == 0) {
          this.tree = this.handleTreeData(res.data, 1);
        }
      }).catch(err => {
        this.isShowLoading(false);
      });

      if (this.account && this.account.account == 'root') {
        this.$store.dispatch('getSiteInfo');
      }
    },

    handleTreeData(data, level) {
      data.forEach((item, index, array) => {
        array[index].expand = level < 2;
        if (item.children && item.children.length) {
          const lev = level + 1;
          this.handleTreeData(item.children, lev);
        }
      });
      return data;
    },

    treeSelectChange(data) {
      if (data && data.length) {
        const result = data[0];
        // console.log(result);
        this.id = result.id;
        for (let k in this.params) {
          if (k in result) {
            this.params[k] = result[k];
          }
        }
      }
    },

    treeCheckChange(data) {
      this.checked = data;
    },

    /**
     * [openIcon 选择图标]
     * @return {[type]} [description]
     */
    openIcon() {
      this.iconObj = {
        show: true,
        type: this.params.icon
      };
    },

    openEdit() {
      this.editObj = {
        show: true,
        data: this.tree
      };
    },

    /**
     * [selectIconSuccess 图标选择成功触发事件]
     * @param  {[type]} icon [description]
     * @return {[type]}      [description]
     */
    selectIconSuccess(icon) {
      this.params.icon = icon;
    },

    numberBlur() {
      this.$nextTick(() => {
        let val = this.params.displayorder;
        if (!isIntNum(val)) {
          if (val) {
            val = parseInt(val);
          } else {
            val = 0;
          }
        }
        this.params.displayorder = val;
      });
    },

    /**
     * [destroy 批量删除]
     * @return {[type]} [description]
     */
    destroy() {
      let ids = [];
      if (!this.checked.length) {
        this.$Message.info('请勾选要删除的数据');
        return;
      }

      this.$Modal.confirm({
        title: '确认执行删除操作？',
        onOk: () => {
          this.checked.forEach(item => {
            ids.push(item.id);
          });

          API.destroy({
            ids: ids.join(',')
          }).then(res => {
            if (res.code == 0) {
              // 如果删除的是包含当前编辑项，清空编辑项
              if (ids.includes(this.id)) {
                this.id = '';
                this.clear();
              }
              this.$Message.success('删除成功');
              this.checked = [];
              this.index();
            }
          });
        }
      });
    },

    save() {
      if (!this.params.title) {
        this.$Message.info('请填写名称');
        return;
      }

      if (!this.params.name) {
        this.$Message.info('请填写标识');
        return;
      }

      if (!(/^[a-zA-Z][\s\S]{0,29}/.test(this.params.name))) {
        this.$Message.info('标识以英文字母开头,长度在1-30之间');
        return;
      }

      if (this.params.type) {
        // 操作按钮
        if (!this.params.description) {
          this.$Message.info('请选择按钮权限类型');
          return;
        }
      } else {
        // 页面菜单
        if (!this.params.description) {
          this.$Message.info('请填写描述');
          return;
        }

        if (!this.params.path) {
          this.$Message.info('请填写路径');
          return;
        }

        if (this.params.open == 2) {
          if (this.params.height < 100) {
            this.$Message.info('打开方式为弹出窗口，最小高度为100');
            return;
          }

          if (this.params.width < 100) {
            this.$Message.info('打开方式为弹出窗口，最小宽度为100');
            return;
          }
        }

        if (!this.params.icon) {
          this.$Message.info('请选择图标');
          return;
        }
      }

      if (this.params.displayorder === '') {
        this.$Message.info('请填写排序');
        return;
      }

      let data = this.deepClone(this.params);
      this.loading = true;
      API.update(data, this.id).then(res => {
        this.loading = false;
        if (res.code == 0) {
          this.$Message.success('修改成功');
          this.index();
        }
      }).catch(err => {
        this.loading = false;
      });
    },

    /**
     * [clear 清空]
     * @return {[type]} [description]
     */
    clear() {
      for (let k in this.params) {
        if (['type', 'displayorder', 'open', 'height', 'width'].includes(k)) {
          this.params[k] = 0;
        } else if (k == 'status') {
          this.params[k] = 1;
        } else {
          this.params[k] = '';
        }
      }
    }
  }
};
