import * as API from 'api/virtual/properties';

export default {
  name: 'Products',
  components: {
    UiEdit: resolve => require(['views/virtual/properties/edit'], resolve),
    UiSettings: resolve => require(['views/virtual/properties/settings'], resolve)
  },
  data() {
    return {
      properties: [],
      showData: [],
      params: {
        company_id: '',
        package_id: ''
      },
      only: ['company_id', 'package_id', 'product', 'vehicle', 'commercial_vehicle', 'company', 'platform', 'customer', 'province'],
      updates: [],
      settingsShow: false,
      settingsData: {},
      editModel: false,
      editObj: {
        show: false,
        isUpdate: false,
        data: null
      },
      search: {
        show: true
      },
      page: {
        total: 0,
        limit: 10,
        page: 1
      },
      companies: [],
      companyFilters: [],
      packages: [],
      packageFilters: [],
      data: [],
      columns: [
        {
          title: '序号',
          key: '',
          width: 80,
          render: (h, context) => {
            return h('span', context.row._index + 1);
          }
        },
        {
          title: '企业名称',
          key: 'company_name',
          width: 210,
          tooltip: true
        },
        {
          title: '套餐名称',
          key: 'package_name',
          width: 120
        },
        {
          title: '月流量',
          key: 'flows',
          width: 100
        },
        {
          title: '销售数量',
          key: 'counts',
          width: 100
        },
        {
          title: '公司类型',
          key: 'company',
          minWidth: 170,
          render: (h, context) => {
            return this.editRender('company', h, context);
          }
        },
        {
          title: '产品类型',
          key: 'product',
          minWidth: 130,
          render: (h, context) => {
            return this.editRender('product', h, context);
          }
        },
        {
          title: '套餐类型',
          key: 'package_type',
          width: 100,
          render: (h, context) => {
            return h('span', this.productPackageTypes[context.row.product]);
          }
        },
        {
          title: '平台/API',
          key: 'platform',
          minWidth: 120,
          render: (h, context) => {
            return this.editRender('platform', h, context);
          }
        },
        {
          title: '车辆类型',
          key: 'vehicle',
          minWidth: 120,
          render: (h, context) => {
            return this.editRender('vehicle', h, context);
          }
        },
        {
          title: '商用车分类',
          key: 'commercial_vehicle',
          minWidth: 120,
          render: (h, context) => {
            return this.editRender('commercial_vehicle', h, context);
          }
        },
        {
          title: '客户类型',
          key: 'customer',
          minWidth: 120,
          render: (h, context) => {
            return this.editRender('customer', h, context);
          }
        },
        {
          title: '销售省份',
          key: 'action',
          width: 150,
          render: (h, {
            row,
            column,
            index
          }) => {
            let html = [];

            if (this.haveJurisdiction('update')) {
              let button = h('Button', {
                props: {
                  type: row.province ? 'success' : 'error',
                  size: 'small'
                },
                class: ['btn'],
                on: {
                  click: (event) => {
                    this.editObj = { show: true, data: row, isUpdate: this.editModel };
                  }
                }
              }, this.editModel ? '设置' : '查看');

              html.push(h('Tooltip', {
                props: {
                  content: row.province ? '已设置' : '省份未设置'
                }
              }, [button]));
            }

            if (html.length) {
              return h('div', html);
            }
          }
        }
      ]
    };
  },
  watch: {
    editModel(value) {
      this.columns = this.columns;
      this.$refs.table.handleResize();
    }
  },
  computed: {
    productPackageTypes() {
      let obj = {};

      let packages = this.settingsData.package ? this.settingsData.package : {};

      for (const key in packages) {
        const element = packages[key];

        for (let index = 0; index < element.length; index++) {
          const value = element[index];
          obj[value] = key;
        }
      }

      return obj;
    }
  },
  created() {
    this.index();
    this.settings();
  },
  methods: {
    editRender(key, h, context) {
      if (!this.editModel) {
        return h('span', context.row[key]);
      }

      let options = [];

      let arr = (key === 'product') ? Object.values(this.settingsData['package']).join(",").split(",") : this.settingsData[key];

      for (let index = 0; index < arr.length; index++) {
        const element = arr[index];
        options.push(h('Option', {
          props: {
            value: element
          }
        }, element));
      }

      return h('Select', {
        props: {
          value: context.row[key],
          size: 'small'
        },
        on: {
          input: (value) => {
            let index = (this.page.page - 1) * this.page.limit + context.index;
            this.properties[index][key] = value;
            this.changePage(this.page.page);
            this.updates[index] = this.properties[index];
          }
        }
      }, options);
    },
    /**
     * [index 列表]
     * @param  {Number} company_id [description]
     * @return {[type]}      [description]
     */
    index(page = 1) {
      if (!this.properties.length) {
        this.isShowLoading(true);
        API.index().then(res => {
          if (res.code === 0) {
            this.properties = res.data;
            this.changePage(page);
            this.complete();
          }
          this.isShowLoading(false);
        });
      } else {
        this.changePage(page);
      }
    },
    complete() {
      let companies = {};

      this.properties.map(function(item) {
        companies[item.company_id] = item.company_name;
      });

      let companyArray = [];

      for (const key in companies) {
        companyArray.push({ id: key, name: companies[key] });
      }

      this.companies = companyArray;

      let packages = {};

      this.properties.map(function(item) {
        packages[item.package_id] = item.package_name;
      });

      let packageArray = [];

      for (const key in packages) {
        packageArray.push({ id: key, name: packages[key] });
      }

      this.packages = packageArray;
    },
    /**
     * [request 刷新]
     * @return {[type]} [description]
     */
    request() {
      this.properties = [];
      this.index();
    },
    resetSearch() {
      for (let k in this.params) {
        this.params[k] = '';
      }
      this.index(1);
    },
    changeLimit(limit) {
      this.page.limit = limit;
      this.changePage(1);
    },
    changePage(page) {
      this.page.page = page;

      let properties = JSON.parse(JSON.stringify(this.properties));

      if (this.params.company_id !== '' && this.params.company_id !== undefined) {
        properties = properties.filter(el => { return el.company_id == this.params.company_id; });
      }

      if (this.params.package_id !== '' && this.params.package_id !== undefined) {
        properties = properties.filter(el => { return el.package_id == this.params.package_id; });
      }

      if (this.params.status !== '' && this.params.status !== undefined) {
        if (this.params.status === 0) {
          properties = properties.filter(el => { return el.product !== '' && el.province !== null; });
        } else if (this.params.status === 1) {
          properties = properties.filter(el => { return el.product === '' || el.province === null; });
        }
      }

      this.page.total = properties.length;

      this.showData = properties.slice((page - 1) * this.page.limit, page * this.page.limit);
    },
    settings() {
      if (!this.settingsData.length) {
        API.settings().then(res => {
          if (res.code === 0) {
            this.settingsData = res.data;
          }
        });
      }
    },
    updateSettings(values) {
      this.settingsData = values;
    },

    ok() {
      if (!this.updates.length) {
        this.$Message.warning('数据未修改');
        this.editModel = false;
        return;
      }

      this.isShowLoading(true);

      let updates = [];

      for (let index = 0; index < this.updates.length; index++) {
        const element = this.updates[index];
        let obj = {};
        for (const key in element) {
          if (this.only.indexOf(key) !== -1) {
            obj[key] = element[key];
          }
        }
        updates.push(obj);
      }

      API.store({ data: updates }).then(res => {
        if (res.code === 0) {
          this.updates = [];
          this.editModel = false;
        }
        this.isShowLoading(false);
      });
    },
    handleProvinceSuccess(data) {
      let index = (this.page.page - 1) * this.page.limit + data._index;
      this.properties[index] = data;
      this.changePage(this.page.page);
      this.updates[index] = this.properties[index];
    },
    exportExcel() {
      let params = {};

      for (const key in this.params) {
        const element = this.params[key];

        if (element !== '' && element !== undefined) {
          params[key] = element;
        }
      }

      this.isShowLoading(true);

      API.exportExcel(params).then(res => {
        if (res.code === 0) {
          if (res.data) {
            this.downloadFile(res.data);
          } else {
            this.$Modal.success({
              title: '提示',
              content: '当前导出数据量大，已进入后台队列导出模式，请稍后至导出列表查看下载。'
            });
          }
        }
        this.isShowLoading(false);
      }).catch(() => {
        this.isShowLoading(false);
      });
    },
    importExcel(file) {
      this.isShowLoading(true);
      API.importExcel(file).then(res => {
        if (res.code === 0) {
          this.request();
          this.$Message.success(res.message);
        }

        this.isShowLoading(false);
      });

      return false;
    }
  }
};
