import React, { Component } from 'react';
import DataTable from '@/components/common/DataTable';
import {
  Button,
  Dropdown,
  Menu,
  Space,
  Table,
  DatePicker,
  message,
  Popconfirm
} from "antd";
import {EllipsisOutlined, PlusOutlined} from "@ant-design/icons";
import { TableDropdown } from '@ant-design/pro-table';
import { ProFormSelect } from '@ant-design/pro-form';
import TableModal from './components/TableModal';
import BillingHistory from './components/billingHistory';

import {
  getSelectSuperId,
  getFakeCaptcha
} from './services/API';

import {
  getProcessStatus,
  getLiquidationStatus,
  getApprovedState,
  getNewOrderStatus
} from "@/utils/tools";
import {fakeAccountLogin} from "@/services/login";

const { RangePicker } = DatePicker;

const menu = (
  <Menu>
    <Menu.Item key="1">1st item</Menu.Item>
    <Menu.Item key="2">2nd item</Menu.Item>
    <Menu.Item key="3">3rd item</Menu.Item>
  </Menu>
);

// 部门
const departmentList = async() => {
  const msg = await getSelectSuperId();
  if(msg.error.length === 0){
    let theArr = [];
    msg.data.forEach((item) => {
      theArr.push({
        label: item.name,
        value: item.id
      });
    });
    return theArr;
  }else{
    message.info(msg.error[0].message)
  }
  return [];
}

class Billing extends Component{
  constructor(props) {
    super(props);
    this.state = {
      columns: [
        {
          title: '合同编号',
          dataIndex: 'contractNo',
          width: 200,
          searchBool: true,
        },
        {
          title: '订单编号',
          dataIndex: 'orderNo',
          width: 200,
          searchBool: true,
        },
        {
          title: '客户名称',
          dataIndex: 'userName',
          searchBool: true,
          render: text => {
            return text && text.length > 9 ? text.substr(0, 9) + '...' : text;
          },
        },
        {
          title: '订单部门',
          dataIndex: 'depName',
          key: 'depId',
          width: 200,
          searchBool: true,
          renderFormItem: () => {
            return (
              <ProFormSelect label='' request={departmentList}/>
            );
          },
        },
        {
          title: '下单时间',
          dataIndex: 'createDate',
          key: 'createDate',
          valueType: 'dateRange',
          searchBool: true,
          render: (text, record) => {
            return record.createDate;
          }
        },
        {
          title: '合同签订时间',
          dataIndex: 'signDate',
          width: 200,
        },
        {
          title: "流程状态",
          dataIndex: "processStatus",
          key: "processStatus",
          render: text => {
            return getProcessStatus(text);
          }
        },
        {
          title: '签单金额(万元)',
          dataIndex: 'totalAmount',
          width: 200,
          searchBool: true,
          renderFormItem: () => {
            return (
              <ProFormSelect label='' valueEnum={{
                '0': {
                  text: '10万元以下',
                },
                '1': {
                  text: '10~20万元',
                },
                '2': {
                  text: '20~30万元',
                },
                '3': {
                  text: '30~40万元',
                },
                '4': {
                  text: '20~40万元以上',
                },
              }}/>
            );
          }
        },
        {
          title: "开票金额(万元)",
          dataIndex: "invoiceAmount",
          key: "invoiceAmount"
        },
        {
          title: "已收款(万元)",
          dataIndex: "settlementAmount",
          key: "settlementAmount"
        },
        {
          title: "结算状态",
          dataIndex: "liquidationStatus",
          key: "liquidationStatus",
          searchBool: true,
          renderFormItem: () => {
            return (
              <ProFormSelect label='' valueEnum={{
                '0': {
                  text: '首付待付请',
                },
                '1': {
                  text: '尾款待付清',
                },
                '2': {
                  text: '已付清',
                }
              }}/>
            );
          },
          render: text => {
            return getLiquidationStatus(text);
          }
        },
        {
          title: "是否特批",
          dataIndex: "approval",
          key: "approval",
          searchBool: true,
          renderFormItem: () => {
            return (
              <ProFormSelect label='' valueEnum={{
                '0': {
                  text: '非特批',
                },
                '1': {
                  text: '特批',
                },
              }}/>
            );
          },
          render: text => {
            return getApprovedState(text);
          }
        },
        {
          title: "订单状态",
          dataIndex: "orderStatus",
          key: "orderStatus",
          render: text => {
            return getNewOrderStatus(text);
          }
        },
        {
          title: "财务负责人",
          dataIndex: "financeName",
          key: "financeName"
        },
        // {
        //   title: '自定义筛选',
        //   key: 'direction',
        //   hideInTable: true,
        //   dataIndex: 'direction',
        //   searchBool: true,
        //   search: {
        //     transform: (v)=>{
        //       console.log(v)
        //       return v
        //     }
        //   },
        //   renderFormItem: (item, props) => {
        //     return (
        //       <ProFormSelect request={departmentList}/>
        //     );
        //   },
        // },
        {
          title: '操作',
          valueType: 'option',
          key: 'option',
          fixed: 'right',
          align: 'center',
          width: 150,
          render: (text, record, key, action) => [
            <a
              key="editable"
              onClick={(e) => {
                e.stopPropagation();
                this.visit(record, key);
              }}
            >
              开票
            </a>,
            <Popconfirm
              title="是否结项?"
              onConfirm={(e) => {
                e.stopPropagation();
                this.delectRow(record.orderNo,action);
              }}
              onCancel={(e)=>{e.stopPropagation();}}
              okText="是"
              cancelText="否"
            >
              <a
                target="_blank"
                rel="noopener noreferrer"
                key="view"
                onClick={(e)=>{
                  e.stopPropagation();
                }}
              >
                结项
              </a>
            </Popconfirm>,
            <TableDropdown
              key="actionGroup"
              onSelect={(v) => {
                // 操作
                console.log(v)
              }}
              menus={[
                { key: 'copy', name: '复制' },
                { key: 'delete', name: '删除' },
              ]}
            />,
          ],
        },
      ],
      tableModal: false,
      tableRowInfor: {},
      billingHistoryModal: false,
      billinghistoryorderNo: '',
    }
    this.dataTableRef = null;
  }

  componentDidMount() {

  }

  // 结项
  async delectRow(orderNo,action) {
    const msg = await getFakeCaptcha(orderNo);
    if(msg.error.length === 0){
      message.success("该项目已成功结项！");
      action.reload();
    }else{
      message.info(msg.error[0].message)
    }
  }

  render() {
    return (
      <>
        <DataTable
          ref={res => this.dataTableRef = res}
          headerTitle='开单与签单'
          url='/api/admin/newOrder/orderNewList'
          rowKey='orderNo'
          scroll={{ x: 2500 }}
          columns={this.state.columns}
          search={{
            filterType: 'query',
            labelWidth: 'auto',
            defaultCollapsed: false,
          }}
          rowSelection={{
            type: 'radio',
            selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
          }}
          requestProcess={(v)=>{
            if(v && v.createDate){
              v.starTime = v.createDate[0];
              v.endTime = v.createDate[1];
              delete v.createDate;
            }
            return v;
          }}
          onRow={record => {
            return {
              onClick: (event) => {
                this.setState({
                  tableModal: true,
                  tableRowInfor: record,
                })
              }, // 点击行
            };
          }}
          onHeaderRow={column => {
            return {
              onClick: () => {}, // 点击表头行
            };
          }}
          toolBarRender={[
            <Button key="button" icon={<PlusOutlined />} type="primary">
              开单
            </Button>,
            <Dropdown key="menu" overlay={menu}>
              <Button>
                <EllipsisOutlined />
              </Button>
            </Dropdown>,
          ]}
          tableAlertRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => (
            <Space size={24}>
              <span>
                已选 {selectedRowKeys.length} 项
                <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                  取消选择
                </a>
              </span>
              <span>{`签单金额: ${selectedRows.reduce(
                (pre, item) => pre + item.totalAmount,
                0,
              )} 万`}</span>
            </Space>
          )}
          tableAlertOptionRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => {
            return (
              <Space size={16}>
                <a onClick={()=>{
                  this.setState({
                    billingHistoryModal: true,
                    billinghistoryorderNo: selectedRowKeys[0],
                  })
                }}>查看开票记录</a>
                <a>查看催款详情</a>
                <a>查看项目进度</a>
              </Space>
            );
          }}
        />
        <TableModal
          centered
          width={1200}
          visible={this.state.tableModal}
          tableRowInfor={this.state.tableRowInfor}
          onCancel={() => this.setState({
            tableModal: false,
            tableRowInfor: {}
          })}
          onOk={() => this.setState({
            tableModal: false,
            tableRowInfor: {},
          })}/>
        {/* 开票历史记录 */}
        <BillingHistory
          visible={this.state.billingHistoryModal}
          orderNo={this.state.billinghistoryorderNo}
          onCancel={() => this.setState({
            billingHistoryModal: false,
            billinghistoryorderNo: '',
          })}
          onOk={() => this.setState({
            billingHistoryModal: false,
            billinghistoryorderNo: '',
          })}
        />
      </>
    );
  }
}

export default Billing;
