import { config, dataUtils, enums, stringUtils } from '@utils';
import { DatePicker, Input, message, Select, Tooltip } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import React from 'react';
import { DataTable, MonthPicker, SuggestSelect, UdcSelect } from '../../../components';
import { consolidateStreamedStyles } from 'styled-components';
const { api } = config;
const { excel } = api;
const { exportExcelURL } = excel;
const Option = Select.Option;
const RangePicker = DatePicker.RangePicker;
const InquiryForm = ({ dispatch, inquiryForm, loading }) => {
  const {
    list, total, suppFlag, addBtnFlag, editBtnFlag, viewBtnFlag, exportBtnFlag,
    deleteBtnFlag, copyBtnFlag, approvalBtnFlag, previewBtnFlag, yijiaBtnFlag, yjconfirmBtnFlag, yjAdjustBtnFlag
  } = inquiryForm;
  const domain = 'inquiryForm';
  const handleMonthChange = (value) => {
    // console.warn('change val', value);
  };
  const { peStatus } = enums;

  //比价结果导出
  const handleExport = (url) => {
      const a = document.createElement('a');
      // a.style = 'display: none';
      a.style.display = 'none';
      // a.download = fileName;
      a.href = url;
      a.target = '_blank';

      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
  };

  const tableProps = {
    rowKey: 'id',
    limit: stringUtils.queryURL('limit'),
    offset: stringUtils.queryURL('offset'),
    sortBy: stringUtils.queryURL('sortBy') || 'id',
    sortDirection: stringUtils.queryURL('sortDirection') || 'DESC',
    scroll: {
      x: '250%',
    },
    showAdd: addBtnFlag ? (!suppFlag) : false,
    showEdit: false,
    showDelete: false,
    showView: viewBtnFlag,
    domain,
    dispatch,
    loading,
    total,
    dataSource: list,
    rowSelection: {
      type: 'checkbox',
    },
    filter: [{
      title: '询价单',
      dataIndex: 'docCodeName',
      options: {
        initialValue: stringUtils.queryURL('docCodeName'),
      },
      tag: <Input placeholder="请输入询价单号/名称"/>,
    }, {
      title: '询价单状态',
      dataIndex: 'docStatus',
      tag: <UdcSelect domain="SRM" code="PE_STATUS"/>,
      options: {
        initialValue: stringUtils.queryURL('docStatus'),
      },
    }, {
      title: '询价人',
      dataIndex: 'createUser',
      options: {
        initialValue: stringUtils.queryURL('createUser'),
      },
      tag: <Input placeholder="请输入询价人编号/名称"/>,
    }, {
      title: '供应商',
      dataIndex: 'suppCodeName',
      options: {
        initialValue: stringUtils.queryURL('suppCodeName'),
      },
      tag: <Input placeholder="请输入供应商编号/名称"/>,
    }, {
      title: '供货区域',
      dataIndex: 'suppCenterId',
      options: {
        rules: [
          {
            required: false,
            message: '必填',
          },
        ],
      },
      tag: <SuggestSelect apiName="regions"/>,
    }, {
      title: '是否已报价',
      dataIndex: 'quoteFlag',
      options: {
        initialValue: stringUtils.queryURL('quoteFlag'),
      },
      tag: <Select
        defaultActiveFirstOption={false}
        style={{ width: '100%' }}
        filterOption={false}
        allowClear
      >
        <Option key='1' title='是'>是</Option>
        <Option key='0' title='否'>否</Option>
      </Select>,
    }, {
      title: '是否已议价',
      dataIndex: 'bargainFlag',
      options: {
        initialValue: stringUtils.queryURL('bargainFlag'),
      },
      tag: <Select
        defaultActiveFirstOption={false}
        style={{ width: '100%' }}
        filterOption={false}
        allowClear
      >
        <Option key='1' title='是'>是</Option>
        <Option key='0' title='否'>否</Option>
      </Select>,
    }, {
      title: '议价是否确认',
      dataIndex: 'bargainConfirmFlag',
      options: {
        initialValue: stringUtils.queryURL('bargainConfirmFlag'),
      },
      tag: <Select
        defaultActiveFirstOption={false}
        style={{ width: '100%' }}
        filterOption={false}
        allowClear
      >
        <Option key='1' title='是'>是</Option>
        <Option key='0' title='否'>否</Option>
      </Select>,
    }, {
      title: '任务节点',
      dataIndex: 'activeTaskKey',
      options: {
        initialValue: stringUtils.queryURL('activeTaskKey'),
      },
      tag: <SuggestSelect apiName="taskDefs" params={{ defKeys: ['Inquiry'] }} optionKey="code"/>,
    }, {
      title: '流程状态',
      dataIndex: 'bpmStatus',
      options: {
        initialValue: stringUtils.queryURL('bpmStatus') || 'NONE',
      },
      tag: <UdcSelect domain="SRM" code="TRANSACT_STATUS"/>,
    }],
    columns: [{
      title: '询价单编号',
      dataIndex: 'docNo',
      width: '6%',
      className: 'noWrap',
      // sorter: true,
    },{
      title: '供货区域',
      dataIndex: 'suppCenterName',
      width: '6%',
      className: 'noWrap',
    }, {
      title: '询价单名称',
      dataIndex: 'peName',
      width: '6%',
      className: 'alignLeft',
      sorter: true,
      render: (value, row, index) => {
        if (value) {
          return (value.length > 10 ? (
            <Tooltip placement="bottom" title={value}>{value && `${value.slice(0, 10)}...`}</Tooltip>) : value);
        } else {
          return '';
        }
      },
    }, {
      title: '供应商编号',
      dataIndex: 'suppCode',
      width: '6%',
      className: 'noWrap',
      sorter: true,
    }, {
      title: '供应商名称',
      dataIndex: 'suppName',
      width: '7%',
      className: 'alignLeft',
      sorter: true,
      render: (value, row, index) => {
        if (value) {
          return (value.length > 10 ? (
            <Tooltip placement="bottom" title={value}>{value && `${value.slice(0, 10)}...`}</Tooltip>) : value);
        } else {
          return '';
        }
      },
    }, {
      title: '询价单状态',
      dataIndex: 'docStatusName',
      width: '4%',
      className: 'noWrap',
    }, {
      title: '当前任务',
      dataIndex: 'activeTaskName',
      className: 'alignLeft',
      width: '6%',
    }, {
      title: '报价截止时间',
      dataIndex: 'deadlineTime',
      className: 'noWrap',
      width: '7%',
      // render: (value, row, index) => {
      //   return (<span>{dataUtils.ymd(value)}</span>);
      // },
      // sorter: true,
    }, {
      title: '议价截止时间',
      dataIndex: 'deadlineHourText',
      className: 'noWrap',
      width: '7%',
    }, {
      title: '询价周期',
      dataIndex: 'quotePeriodName',
      width: '5%',
    }, {
      title: '价格生效期间',
      className: 'noWrap',
      width: '8%',
      render: (value, row, index) => {
        return (<span>{row.priceEffectDate}-{row.priceExpireDate}</span>);
      },
    },{
      title: '供方联系人',
      dataIndex: 'suppLinkMan',
      width: '4%',
      className: 'alignLeft',
      sorter: true,
    },
      {
        title: '联系人电话',
        dataIndex: 'suppLinkTel',
        width: '5%',
        className: 'noWrap',
        sorter: true,
      },  /*{
      title: '订货周期',
      dataIndex: '1',
      width: '6%',
      className: 'alignRight',
    }, {
      title: '起送量',
      dataIndex: '2',
      width: '4%',
      className: 'alignRight',
    }, {
      title: '起送金额',
      dataIndex: '3',
      width: '5%',
      className: 'alignRight',
    }, */{
        title: '创建人',
        dataIndex: 'createUserName',
        className: 'alignLeft',
        width: '4%',
        sorter: true,
      }, {
        title: '创建时间',
        dataIndex: 'createTime',
        width: '6%',
        className: 'noWrap',
        render: (value, row, index) => {
          return (<span>{dataUtils.ymd(value)}</span>);
        },
        sorter: true,
      },{
        title: '是否已报价',
        dataIndex: 'quoteFlag',
        width: '4%',
        className: 'noWrap',
        sorter: false,
        render: (value, row, index) => {
          return (<span>{value==='1'?'是':'否'}</span>);
        },
      }, {
        title: '是否已议价',
        dataIndex: 'bargainFlag',
        width: '4%',
        className: 'noWrap',
        sorter: false,
        render: (value, row, index) => {
          return (<span>{value==='1'?'是':'否'}</span>);
        },
      }, {
        title: '议价已确认',
        dataIndex: 'bargainConfirmFlag',
        width: '4%',
        className: 'noWrap',
        sorter: false,
        render: (value, row, index) => {
          return (<span>{value==='1'?'是':'否'}</span>);
        },
      }],
    buttons: [{
      key: 'edit',
      type: 'primary',
      name: '修改',
      hidden: editBtnFlag ? suppFlag : true,
      requiredSelected: 1,
      cb: (selectedRowKeys, searchBarForm, selectedRows) => {
        if (peStatus.DELETE === selectedRows[0].docStatus) {
          message.warn('已作废的询价单不能修改');
        } else {
          dispatch({
            type: `${domain}/getSingle`,
            payload: {
              mode: 'update',
              id: selectedRowKeys[0],
            },
          });
        }
      },
    }, {
      key: 'yijia',
      type: 'primary',
      name: '议价',
      hidden: yijiaBtnFlag ? suppFlag : true,
      requiredSelected: 1,
      cb: (selectedRowKeys, searchBarForm, selectedRows) => {
        if (peStatus.BARGAINING != selectedRows[0].docStatus && peStatus.NO_ACCEPT != selectedRows[0].docStatus) {
          message.warn('仅可操作状态为议价或落选的记录');
        } else {
          dispatch({
            type: `${domain}/getSingle`,
            payload: {
              mode: 'quote',
              id: selectedRowKeys[0],
            },
          });
        }
      },
    }, {
      key: 'yjAdjust',
      type: 'primary',
      name: '议价时间调整',
      hidden: yjAdjustBtnFlag ? suppFlag : true,
      requiredSelected: 1,
      cb: (selectedRowKeys, searchBarForm, selectedRows) => {
        if (peStatus.BARGAINING != selectedRows[0].docStatus) {
          message.warn('仅可操作状态为议价的记录');
        } else {
          dispatch({
            type: `${domain}/getSingle`,
            payload: {
              mode: 'yjAdjust',
              id: selectedRowKeys[0],
            },
          });
        }
      },
    }, {
      key: 'yjConfirm',
      type: 'primary',
      name: '议价确认',
      hidden: yjconfirmBtnFlag ? !suppFlag : true,
      requiredSelected: 1,
      cb: (selectedRowKeys, searchBarForm, selectedRows) => {
        if (peStatus.BARGAINING === selectedRows[0].docStatus && selectedRows[0].bargainFlag === '1') {
          dispatch({
            type: `${domain}/getSingle`,
            payload: {
              mode: 'yjconfirm',
              id: selectedRowKeys[0],
            },
          });
        } else {
          message.warn('仅可操作状态为 议价中 并且 已经进行议价 的询价单');
        }
      },
    }, {
      key: 'delete',
      type: 'primary',
      name: '作废',
      requiredSelected: 2,
      hidden: deleteBtnFlag ? suppFlag : true,
      cb: (selectedRowKeys, searchBarForm, selectedRows) => {
        let canBeDeleted = true;
        for (let row of selectedRows) {
          switch (row.docStatus) {
            case peStatus.COMPARING:
              canBeDeleted = false;
              message.warn(`询价单: ${row.docNo} 处于比价中，不能进行作废操作`);
              break;
            case peStatus.COMPARE_AUDIT:
              canBeDeleted = false;
              message.warn(`询价单: ${row.docNo} 处于比价审核中，不能进行作废操作`);
              break;
            case peStatus.QUOTE_EXPIRE:
              canBeDeleted = false;
              message.warn(`询价单: ${row.docNo} 逾期未报价，不能进行作废操作`);
              break;
            case peStatus.NO_ACCEPT:
              canBeDeleted = false;
              message.warn(`询价单: ${row.docNo} 已落选，不能进行作废操作`);
              break;
            case peStatus.DELETE:
              canBeDeleted = false;
              message.warn(`询价单: ${row.docNo} 已作废，不能进行作废操作`);
              break;
            case peStatus.FINISH:
              canBeDeleted = false;
              message.warn(`询价单: ${row.docNo} 已完成，不能进行作废操作`);
              break;
            default:
          }
          if (!canBeDeleted) {
            break;
          }
        }
        if (canBeDeleted) {
          dispatch({
            type: `${domain}/delete`,
            payload: { ids: selectedRowKeys, },
          });
        }
      },
    }, {
      key: 'copy',
      type: 'primary',
      name: '复制',
      hidden: copyBtnFlag ? suppFlag : true,
      requiredSelected: 1,
      cb: (selectedRowKeys, searchBarForm, selectedRows) => {
        // console.log("selectedRows==>",selectedRows);
        dispatch({
          type: `${domain}/copy`,
          payload: { mode: 'create', id: selectedRowKeys[0], },
        });
      },
    }, {
      key: 'approval',
      type: 'primary',
      name: '审批',
      hidden: approvalBtnFlag ? suppFlag : true,
      requiredSelected: 1,
      cb: (selectedRowKeys, searchBarForm, selectedRows) => {
        if (peStatus.DELETE === selectedRows[0].docStatus) {
          message.warn('已作废的询价单不能审批');
        } else {
          dispatch({
            type: `${domain}/getSingle`,
            payload: { mode: 'approval', id: selectedRowKeys[0], },
          });
        }
      },
    }, {
      key: 'preview',
      type: 'primary',
      name: '查看报价明细',
      hidden: previewBtnFlag ? suppFlag : true,
      requiredSelected: 1,
      cb: (selectedRowKeys, searchBarForm, selectedRows) => {
        if (peStatus.DELETE === selectedRows[0].docStatus) {
          message.warn('询价单已作废，没有报价明细');
        } else {
          dispatch({
            type: `${domain}/viewQuote`,
            payload: {
              docNo: selectedRows[0].docNo,
            },
          });
        }
      },
    }, {
      key: 'export',
      type: 'primary',
      name: '比价结果导出',
      requiredSelected: 2,
      hidden: !exportBtnFlag,
      cb: (selectedRowKeys, searchBarForm, selectedRows) => {
        let queryStr = "";
        if (selectedRows.length > 0) {
          for (let i = 0; i < selectedRows.length;i++) {
            if (selectedRows[i].docStatus === "09") {
              if (i === 0) {
                queryStr = queryStr + "docId=" + selectedRowKeys[i];
              } else {
                queryStr = queryStr + "&docId=" + selectedRowKeys[i];
              }
            } else {
              message.warn("未完成的询价单，不能查看比价结果");
              return;
            }
          }
          handleExport(`${exportExcelURL}/compare-result` + "?" + queryStr);
        } else {
          message.warn("请选择需要导出的询价单")
        }
      },
    }],
  };

  return (
    <div className="content-inner">
      <DataTable {...tableProps} />
    </div>
  );

};

export default connect(({ inquiryForm, loading }) => ({ inquiryForm, loading }))(InquiryForm);
