import * as API from 'api/virtual/packages';
export default {
  name: 'Companies',
  components: {
    UiEdit: resolve => require(['views/virtual/packages/edit'], resolve)
  },
  data() {
    return {
      params: {
        name: '',
        carrier_operator: '',
        sn: '',
        status: '',
        flowed: ''
      },
      type: 0,
      trashed: null,
      list_data: null,
      editObj: {
        show: false,
        data: null
      },
      search: {
        show: false
      },
      table_titles: [
        {
          type: 'expand',
          width: 50,
          render: (h, params) => {
            let row = params.row;
            let Col = [];

            Col.push(h('Col', { props: { span: 6 }, class: ['fz-12'] }, '成本价(元): ' + Number(row['cost_price']).toFixed(2)));
            Col.push(h('Col', { props: { span: 6 }, class: ['fz-12'] }, '指导价(元): ' + Number(row['guide_price']).toFixed(2)));
            Col.push(h('Col', { props: { span: 6 }, class: ['fz-12'] }, '语音分钟数: ' + row['voices']));
            Col.push(h('Col', { props: { span: 6 }, class: ['fz-12'] }, '短信条数: ' + row['messages']));
            Col.push(h('Col', { props: { span: 6 }, class: ['fz-12'] }, '短信功能: ' + (row['has_messages'] ? '有' : '无')));
            Col.push(h('Col', { props: { span: 6 }, class: ['fz-12'] }, 'LBS功能: ' + (row['has_lbs'] ? '有' : '无')));
            Col.push(h('Col', { props: { span: 6 }, class: ['fz-12'] }, '重置周期（月）: ' + row['reset_months']));

            if (row['type']) {
              Col.push(h('Col', { props: { span: 6 }, class: ['fz-12'] }, '立即生效: ' + (row['effect_months'] ? '否' : '是')));
            }

            Col.push(h('Col', { props: { span: 6 }, class: ['fz-12'] }, '套餐说明: ' + row['description']));
            Col.push(h('Col', { props: { span: 6 }, class: ['fz-12'] }, '创建时间: ' + row['created_at']));
            Col.push(h('Col', { props: { span: 6 }, class: ['fz-12'] }, '更新时间: ' + row['updated_at']));

            return h('Row', {}, Col);
          }
        },
        {
          title: 'ID',
          key: 'id',
          width: 120
        },
        {
          title: '套餐编号',
          key: 'sn',
          width: 200
        },
        {
          title: '套餐名称',
          key: 'name',
          width: 120
        },
        {
          title: '运营商',
          key: 'carrier_operator_name',
          width: 100
        },
        {
          title: '流量值（M）',
          key: 'flows',
          width: 120
        },
        {
          title: '套餐周期(月)',
          key: 'service_months',
          width: 120
        },
        {
          title: '说明',
          key: 'description',
          minWidth: 100
        },
        {
          title: '状态',
          key: '',
          width: 100,
          render: (h, { row, column, index }) => {
            let type = ['primary', 'warning', 'error'];
            let text = ['已启用', '已禁用', '已删除'];

            return h('Button', {
              props: {
                type: type[row.status],
                size: 'small'
              }
            }, text[row.status]);
          }
        },
        {
          title: '创建时间',
          key: 'created_at',
          width: 170
        },
        {
          title: '操作',
          key: 'action',
          width: 170,
          render: (h, {
            row,
            column,
            index
          }) => {
            row.cost_price = Number(row.cost_price);
            row.guide_price = Number(row.guide_price);
            let html = [];

            if (row.deleted_at) {
              return h('Tag', { props: { color: 'default' } }, '该套餐已被删除');
            }

            if (this.haveJurisdiction('update')) {
              html.push(h('Button', {
                props: {
                  type: 'primary',
                  size: 'small',
                  disabled: false,
                  icon: 'md-create'
                },
                class: ['btn'],
                on: {
                  click: (event) => {
                    this.openEdit(true, row);
                  }
                }
              }, '编辑'));
            }

            if (this.haveJurisdiction('destroy')) {
              html.push(h('Button', {
                props: {
                  type: 'error',
                  size: 'small',
                  disabled: false,
                  icon: 'md-trash'
                },
                class: ['btn'],
                on: {
                  click: () => {
                    this.$Modal.confirm({
                      title: '提示',
                      content: '删除后该企业不可使用，请谨慎操作',
                      onOk: () => {
                        API.destroy({
                          ids: row.id
                        }).then(res => {
                          if (res.code == 0) {
                            this.$Message.success('删除成功');
                            this.request();
                          }
                        });
                      }
                    });
                  }
                }
              }, '删除'));
            }

            if (html.length) {
              return h('div', html);
            }
          }
        }
      ]
    };
  },
  created() {
    this.type = Number(this.$route.params.type);
    this.index(1);
  },
  mounted() {
    if (this.type !== 3) {
      this.table_titles.splice(7, 0, {
        title: '套餐类型',
        key: '',
        width: 100,
        render: (h, { row, column, index }) => {
          let type = ['primary', 'warning'];
          let text = ['正向套餐', '后向套餐'];

          return h('Button', {
            props: {
              type: type[row.flowed],
              size: 'small'
            }
          }, text[row.flowed]);
        }
      });
    }
  },
  methods: {
    /**
     * [index 列表]
     * @param  {Number} page [description]
     * @return {[type]}      [description]
     */
    index(page = 1) {
      let params = Object.assign(this.params, { 'type': this.type, 'orderBy': 'id', 'sortedBy': 'desc' });

      if (params.status === 2) {
        params.status = undefined;
        params.trashed = 'only';
      } else {
        params.trashed = 'without';
      }

      let data = this.searchDataHandle({}, { page }, params);
      this.isShowLoading(true);
      API.index(data).then(res => {
        this.isShowLoading(false);
        if (res.code == 0) {
          this.list_data = res.data;
        }
      }).catch(() => {
        this.isShowLoading(false);
      });
    },

    /**
     * [openEdit 打开编辑弹窗]
     * @return {[type]} [description]
     */
    openEdit(bool, data = null) {
      this.editObj = {
        show: bool,
        data
      };
    },

    /**
     * [request 刷新]
     * @return {[type]} [description]
     */
    request() {
      const result = this.list_data;
      let page = result.current_page;

      if (this.list_data.data.length == 1) {
        page = this.returnPage(result.total, result.current_page, result.per_page);
      }

      this.index(page);
    },

    resetSearch() {
      for (let k in this.params) {
        this.params[k] = '';
      }
      this.trashed = null;
      this.index(1);
    }
  }
};
