import { Button, Card, Col, Form, message, Modal, Row, Select } from 'antd';
import Axis from 'bizcharts/lib/components/Axis';
import Chart from 'bizcharts/lib/components/Chart';
import Legend from 'bizcharts/lib/components/Legend';
import Tooltip from 'bizcharts/lib/components/Tooltip';

import React from 'react';
import * as DataSet from '@antv/data-set';
import Line from 'bizcharts/lib/components/TypedGeom/Line';
import Point from 'bizcharts/lib/components/TypedGeom/Point';

import { SupplierPicker } from '@bizComponents';
import { MonthPicker, SuggestSelect } from '@components';

const FormItem = Form.Item
const Option = Select.Option

const formItemLayout = {
  colon: false,
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 16,
  },
  style: {
    // marginBottom: 20,
  },
};

const ColProps = {
  xs: 24,
  sm: 24,
  md: 8,
  xl: 8,
  style: {},
};

/**
 *
 * @param key      字段名
 * @param index    行号
 * @param newValue 新值
 */
const handleChange = () => {
};

const modal =
  ({
    mode,
    domain,
    readOnly,
    isSupplier,
    filterParams,
    record,
    webs,
    supps,
    onOk,
    onCancel,
    dispatch,
    loading,
    selectedWeb,
    selectedSupp,
    form: {
      getFieldDecorator,
      validateFields,
      getFieldsValue,
     },
    ...modalProps
   }): React.ReactElement<{}> => {

    const { itemId, newPayload, supplier } = filterParams;
    let needInit = false
    supps.length>0 && supps.map(su => {
      if (supplier && supplier.id && su.id === supplier.id) {
        needInit = true
      }
    })

    const items = [{
      title: '供货区域',
      dataIndex: 'suppCenter',
      options: {
        rules: [{
          required: true,
          message: '必填',
        }],
      },
      tag:
        <SuggestSelect
          title="选择供货区域"
          apiName="itemRgns"
          dataKey="id"
          params={{ itemId: itemId || '' }}
        />,
    }, {
      title: '参考价来源',
      dataIndex: 'webSiteCode',
      options: {
        rules: [{
          required: true,
          message: '必填',
        }],
      },
      tag:
        <Select mode="multiple" style={{ width: '100%' }} onChange={() => handleChange()}>
          <Option value="0">网站1</Option>
          <Option value="1">网站2</Option>
          <Option value="2">网站3</Option>
          <Option value="3">网站4</Option>
          <Option value="4">网站5</Option>
        </Select>,
    }, {
      title: '报价期间',
      dataIndex: 'yearMonthDate',
      options: {
        initialValue: (newPayload && newPayload.yearMonthDateFrom) ? [newPayload.yearMonthDateFrom, newPayload.yearMonthDateTo] : '',
        rules: [{
          required: true,
          message: '必填',
        }],
      },
      tag: <MonthPicker onChange={(val) => handleMonthChange(val)} />,
    }, {
      title: '供应商',
      dataIndex: 'suppIds',
      options: {
        initialValue: needInit ? [supplier.id] : [],
        rules: [{
          required: true,
          message: '必填',
        }],
      },
      tag:
        <SuggestSelect
          title="选择供应商"
          mode="multiple"
          apiName="itemSupps"
          dataKey="id"
          disabled={isSupplier}
          params={{ itemId: itemId || '' }}
        />,
      colProps: {
        xs: 24,
        sm: 24,
        md: 24,
        xl: 24,
      },
      formItemLayout: {
        labelCol: { span: 2 },
        wrapperCol: { span: 20 },
      },
    }];

    const handleMonthChange = (value) => {
    };

    const handleOk = () => {
      if (mode === 'view') {
        onOk({});
        return 0;
      }
      validateFields((errors) => {
        if (errors) {
          return;
        }
        const data = {
          ...getFieldsValue(),
        };

        onOk(data);
      });
    };

    const handleCancel = () => {
      dispatch({ type: 'ouBanks/clearOptions' });
      onCancel();
    };

    const modalOpts = {
      ...modalProps,
      // // onOk: handleOk,
      onCancel: handleCancel,
      footer: [
        <Button key="back" onClick={handleCancel}>取消</Button>,
        // mode !== 'view' &&
        // <Button
        //   key="submit"
        //   type="primary"
        //   loading={mode === 'create' ? loading.effects[`${domain}/create`] : loading.effects[`${domain}/update`]}
        //   onClick={handleOk}
        // >保存</Button>,
      ],
    };

    const renderItem = (item) => {
      return (
        <Col key={item.dataIndex} {...ColProps} {...item.colProps}>
          <FormItem
            label={item.title}
            hasFeedback={!readOnly && !item.tag.props.disabled && !!(item.options) && !!(item.options.rules)}
            {...formItemLayout}
            {...item.formItemLayout}
          >
            {getFieldDecorator(item.dataIndex, {
              ...item.options,
              initialValue: record[`${item.dataIndex}`] || (item.options && item.options.initialValue),
            })(item.tag)}
          </FormItem>
        </Col>
      );
    };

    const queryHistory = () => {
      let hasErr = false
      const data = {
        ...getFieldsValue(),
      };
      // console.warn('data', data)
      const keys = Object.keys(data);
      for (let i in keys) {

        // console.warn('key', keys[i], data[keys[i]], typeof data[keys[i]])
        if (Object.prototype.toString.call(data[keys[i]]) === '[object Array]' && data[keys[i]].length === 0) {
          hasErr = true;
        } else if (data[keys[i]] && typeof data[keys[i]] === 'object') {
          const vals = Object.values(data[keys[i]])
          if (vals.indexOf(null) > -1) {
            hasErr = true;
          }
        }

        if (!data[keys[i]]) {
          hasErr = true;
        }
      }

      if (hasErr) {
        message.error('请填写完整所有的过滤条件');
        return;
      }
      dispatch({ type: 'itemPriceHistory/queryHistory', payload: data });
    };

    let webSite1Name, webSite2Name, webSite3Name, webSite4Name, webSite5Name
    const unKnown = '未知'
    for (let i in record) {
      if (record[i].webSite1Name && !webSite1Name) {
        webSite1Name = record[i].webSite1Name
      }
      if (record[i].webSite2Name && !webSite2Name) {
        webSite2Name = record[i].webSite2Name
      }
      if (record[i].webSite3Name && !webSite3Name) {
        webSite3Name = record[i].webSite3Name
      }
      if (record[i].webSite4Name && !webSite4Name) {
        webSite4Name = record[i].webSite4Name
      }
      if (record[i].webSite3Name && !webSite5Name) {
        webSite5Name = record[i].webSite5Name
      }
    }

    // 根据选择的供应商的不同，传递不同的taxPrice
    const newRecord = [record.length>0 && record[0]]; // 经过清洗过的数据（横坐标相同的数据合并）
    record.map((d, idx) => {
      let isPush = false;

      d[`供应商（${d.suppName.trim() || unKnown}）执行价格`] = d.taxPrice;
      d[`网站1（${webSite1Name || unKnown}）价格`] = d.webSite1Price;
      d[`网站2（${webSite2Name || unKnown}）价格`] = d.webSite2Price;
      d[`网站3（${webSite3Name || unKnown}）价格`] = d.webSite3Price;
      d[`网站4（${webSite4Name || unKnown}）价格`] = d.webSite4Price;
      d[`网站5（${webSite5Name || unKnown}）价格`] = d.webSite5Price;

      if (newRecord.length>0) {
        for (let i in newRecord) {
          if (newRecord[i]['month'] === d['month']) {
            Object.assign(newRecord[i], d);
            isPush = false
          } else {
            isPush = true
          }
        }
        isPush && newRecord.push(d)
      }
    });

    const initArr = [];

    const webPriceList = record.length > 0 ? [
      `网站1（${webSite1Name || unKnown}）价格`,
      `网站2（${webSite2Name || unKnown}）价格`,
      `网站3（${webSite3Name || unKnown}）价格`,
      `网站4（${webSite4Name || unKnown}）价格`,
      `网站5（${webSite5Name || unKnown}）价格`,
    ] : [];

    if (supps.length > 0) {
      for (let j in selectedSupp) {
        supps.map(s => {
          if (s.id == selectedSupp[j]) {
            initArr.push(`供应商（${s.name.trim() || unKnown}）执行价格`)
          }
        })
      };
    };

    if (webPriceList.length > 0) {
      for (let i in selectedWeb) {
        initArr.push(webPriceList[selectedWeb[i]])
      }
    }

    const ds = new DataSet();
    const dv = ds.createView().source(newRecord);
    dv.transform({
      type: 'fold',
      fields: initArr, // 展开字段集
      key: 'webSite', // key字段
      value: 'price', // value字段
    });
    const cols = {
      month: {
        range: [0, 1],
      },
    };

    return (
      <Modal {...modalOpts}>
        <Row type="flex" justify="start">
          {items.map(item => renderItem(item))}
        </Row>

        <Button type="primary" onClick={() => queryHistory()}>查询趋势</Button>

        <Card style={{ width: '100%', marginTop: 10 }}>
          {initArr.length > 1 && record.length > 0 ?
            <Chart
              height={500}
              data={dv}
              scale={cols}
              // padding={{ top: 30, right: 50, bottom: 30, left: 70 }}
              forceFit
            >
              <Legend />
              <Axis name="month" />
              <Axis name="price" />
              <Tooltip crosshairs={{ type: 'y' }} />
              <Line position="month*price" size={2} color={'webSite'} shape={'smooth'} />
              <Point position="month*price" size={4} shape={'circle'} color={'webSite'}
                style={{ stroke: '#fff', lineWidth: 1 }} />
            </Chart> :
            <span>暂无数据</span>
          }
        </Card>

      </Modal>
    );
  };

export default Form.create()(modal);
