import React from 'react';
import './index.less';
import Page from '@src/containers/Page';
import Block from '@src/components/Block';
import FilterLayout from '@src/layouts/FilterLayout';
import ActionLayout from '@src/layouts/ActionLayout';
import TableLayout from '@src/layouts/TableLayout';
import { getMap, formatDate, formatMoney, bindSearch } from '@src/services/Tools';
import { asyncSMessage, asyncForm, asyncDelConfirm } from '@src/services/AsyncTools';
import { ServiceParamMap, ServiceKey, MobileArea, RecordSource, ProductTypeMain } from '../../../../Constant';
import { User } from '../../../stores/user';
import { Course } from '../../../stores/course';

const ServiceKeyMap = getMap(ServiceKey, 'value', 'label');
const ProductTypeMainMap = getMap(ProductTypeMain, 'value', 'label');
const RecordSourceMap = getMap(RecordSource, 'value', 'label');
const ServiceParamList = getMap(Object.keys(ServiceParamMap).map(key => {
  return { list: ServiceParamMap[key], key };
}), 'key', 'list');
const ServiceParamRelation = getMap(Object.keys(ServiceParamMap).map(key => {
  return { map: getMap(ServiceParamMap[key], 'value', 'label'), key };
}), 'key', 'map');
export default class extends Page {
  init() {
    this.timeout = null;
    this.mobile = null;
    this.actionList = [{
      key: 'addService',
      type: 'primary',
      name: '添加服务',
    }, {
      key: 'addData',
      type: 'primary',
      name: '添加资料',
    }];

    this.formF = null;
    this.serviceList = [{
      key: 'id',
      type: 'hidden',
    }, {
      key: 'area',
      type: 'select',
      name: '国际码',
      select: MobileArea,
      required: true,
    }, {
      key: 'mobile',
      type: 'input',
      name: '手机号',
      placeholder: '请输入',
      required: true,
      option: {
        normalize: (value) => {
          if (!value) return value;
          if (this.mobile === value) return value;
          if (this.timeout) {
            clearTimeout(this.timeout);
            this.timeout = null;
          }
          this.timeout = setTimeout(() => {
            User.validMobile({ area: this.formF.getFieldValue(), mobile: value }).then(result => {
              this.mobile = value;
              this.serviceList[1].suffix = !result ? '已注册' : '未注册';
              this.formF.setFieldsValue({ load: true });
            });
          }, 1500);
          return value;
        },
      },
    }, {
      key: 'service',
      type: 'select',
      name: '开通服务',
      select: ServiceKey,
      placeholder: '请选择',
      required: true,
      onChange: (value) => {
        this.serviceList[4].select = ServiceParamList[value] || [];
        this.serviceList[4].disabled = !this.serviceList[4].select.length;
        this.formF.setFieldsValue({ param: '' });
      },
    }, {
      key: 'param',
      type: 'select',
      name: '服务参数',
      select: [],
    }];
    this.dataList = [{
      key: 'id',
      type: 'hidden',
    }, {
      key: 'area',
      type: 'select',
      name: '国际码',
      select: MobileArea,
      required: true,
    }, {
      key: 'mobile',
      type: 'input',
      name: '手机号',
      placeholder: '请输入',
      required: true,
      option: {
        normalize: (value) => {
          if (!value) return value;
          if (this.mobile === value) return value;
          if (this.timeout) {
            clearTimeout(this.timeout);
            this.timeout = null;
          }
          this.timeout = setTimeout(() => {
            User.validMobile({ area: this.formF.getFieldValue(), mobile: value }).then(result => {
              this.mobile = value;
              this.dataList[1].suffix = !result ? '已注册' : '未注册';
              this.formF.setFieldsValue({ load: true });
            });
          }, 1500);
          return value;
        },
      },
    }, {
      key: 'dataId',
      type: 'select',
      name: '开通资料',
      required: true,
      select: [],
      placeholder: '请选择',
    }];
    this.filterF = null;
    this.filterForm = [{
      key: 'userId',
      type: 'select',
      allowClear: true,
      name: '用户',
      select: [],
      number: true,
      placeholder: '请输入',
    }, {
      key: 'productType',
      type: 'select',
      allowClear: true,
      name: '种类',
      select: ProductTypeMain,
      onChange: (value) => {
        // 根据服务
        this.changeSearch(this.filterForm, this.filterF, value, null);
        this.filterF.setFieldsValue({ productId: null, service: null });
      },
    }, {
      key: 'productId',
      type: 'select',
      allowClear: true,
      name: '具体名称',
      number: true,
      select: [],
    }, {
      key: 'service',
      type: 'select',
      allowClear: true,
      name: '服务',
      select: ServiceKey,
    }, {
      key: 'source',
      type: 'select',
      allowClear: true,
      name: '开通方式',
      select: RecordSource,
    }];
    this.columns = [{
      title: '用户ID',
      dataIndex: 'userId',
    }, {
      title: '用户手机',
      dataIndex: 'user.mobile',
    }, {
      title: '用户姓名',
      dataIndex: 'user.nickname',
    }, {
      title: '种类',
      dataIndex: 'productType',
      render: (text) => {
        return `${ProductTypeMainMap[text]}`;
      },
    }, {
      title: '权限',
      dataIndex: 'service',
      render: (text, record) => {
        if (record.productType === 'course') {
          return (record.course || {}).title;
        }
        if (record.productType === 'data') {
          return (record.data || {}).title;
        }
        if (record.productType === 'service') {
          return `${ServiceKeyMap[text]}${record.param ? (ServiceParamRelation[record.service] || {})[record.param] || '' : ''}`;
        }
        return '';
      },
    }, {
      title: '开通时间',
      dataIndex: 'time',
      render: (text, record) => {
        return `${record.startTime ? formatDate(record.startTime) : ''} - ${record.endTime ? formatDate(record.endTime) : ''} `;
      },
    }, {
      title: '开通方式',
      dataIndex: 'source',
      render: (text) => {
        return RecordSourceMap[text] || '';
      },
    }, {
      title: '累计消费金额',
      dataIndex: 'user.totalMoney',
      render: (text) => {
        return formatMoney(text);
      },
    }, {
      title: '操作',
      dataIndex: 'handler',
      render: (text, record) => {
        return <div className="table-button">
          {!record.isStop && (
            <a onClick={() => {
              this.stopAction(record.id);
            }}>停用</a>
          )}
        </div>;
      },
    }];
    bindSearch(this.filterForm, 'userId', this, (search) => {
      return User.list(search);
    }, (row) => {
      return {
        title: `${row.nickname} (${row.mobile})`,
        value: row.id,
      };
    }, this.state.search.userId ? Number(this.state.search.userId) : null, null);

    this.changeSearch(this.filterForm, this, this.state.search.productType, this.state.search.productId);
  }

  initFilter() {

  }

  changeSearch(list, component, key, value) {
    if (key === 'service') {
      list[2].disabled = true;
      list[3].disabled = false;
    } else if (key === 'course' || key === 'data') {
      list[2].disabled = false;
      list[3].disabled = true;
      bindSearch(list, 'productId', component, (search) => {
        if (key === 'course') {
          return Course.list(search);
        }
        return Course.listData(search);
      }, (row) => {
        return {
          title: row.title,
          value: row.id,
        };
      }, value ? Number(value) : null, null);
    } else {
      list[2].disabled = true;
      list[3].disabled = true;
    }
    component.setState({ load: false });
  }

  initData() {
    User.listRecord(Object.assign({ needPackage: false }, this.state.search)).then(result => {
      this.setTableData(result.list, result.total);
    });
  }

  addServiceAction() {
    asyncForm('新建服务', this.serviceList, {}, data => {
      return User.addService(data).then(() => {
        asyncSMessage('添加成功!');
        this.refresh();
      });
    }).then(component => {
      this.formF = component;
    });
  }

  addDataAction() {
    asyncForm('新建资料', this.dataList, {}, data => {
      return User.addData(data).then(() => {
        asyncSMessage('添加成功!');
        this.refresh();
      });
    }).then(component => {
      this.formF = component;
      bindSearch(this.dataList, 'dataId', component, (search) => {
        return Course.listData(search);
      }, (row) => {
        return {
          title: row.title,
          value: row.id,
        };
      }, null, null);
    });
  }

  stopAction(id) {
    asyncDelConfirm('停用确认', '是否停用选中记录?', () => {
      return User.stopRecord({ id }).then(() => {
        asyncSMessage('停用成功!');
        this.refresh();
      });
    });
  }

  renderView() {
    return <Block flex>
      <FilterLayout
        show
        ref={(ref) => { if (!this.filterF) { this.filterF = ref; } }}
        itemList={this.filterForm}
        data={this.state.search}
        onChange={data => {
          this.search(data);
        }} />
      <ActionLayout
        itemList={this.actionList}
        selectedKeys={this.state.selectedKeys}
        onAction={key => this.onAction(key)}
      />
      <TableLayout
        columns={this.tableSort(this.columns)}
        list={this.state.list}
        pagination={this.state.page}
        loading={this.props.core.loading}
        onChange={(pagination, filters, sorter) => this.tableChange(pagination, filters, sorter)}
        onSelect={(keys, rows) => this.tableSelect(keys, rows)}
        selectedKeys={this.state.selectedKeys}
      />
    </Block>;
  }
}