import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Icon, Select, message, Table, Divider, Tag, Pagination, Modal, DatePicker } from 'antd';
import { FormattedMessage } from 'umi-plugin-react/locale';
import router from 'umi/router';
import moment from 'moment';
import AuthButton from '@/components/AuthButton';
import withActions from '@/components/ActionList';
import EditIcon from '@/components/EditIcon';
import styles from '../../style/GoodsList.less';
import SelectCity from '../../../components/SelectButton/CitySelect'
import BuildSelect from '../../../components/SelectButton/BuildSelect'
import apis from '../../../services/apis';
import request from '../../../utils/request';
import Navigate from '@/components/Navigate';


const { Option } = Select;
const { MonthPicker, RangePicker, WeekPicker } = DatePicker;

const header = props => {
  const sampleId  = props.location.query.id;
  const sampleName = props.location.query.sampleName;
  const [data, setData] = useState({})
  const [demend, setDemend] = useState({})
  const [contractBusinessList, setContractBusinessList] = useState([])
  const [contractBusinessIndexList, setContractBusinessIndexList] = useState([])
  const [batchDel, setBatchDel] = useState({visable:false,demandIds:''})
  const [addDemand, setAddDemand] = useState({visable:false})

  useEffect(() => {
    if(sampleId){
      getList({ pageNum: 1, pageSize: 10, sampleId: sampleId });
    }else{
      getList({ pageNum: 1, pageSize: 10});
    }
    
  }, [])

  // 查询列表
  const getList = (params) => {
    console.log(params);
    request({ ...apis.taEcontract.taContractBusinessList, params: { ...params } }).then((data) => {
      console.log(data)
      setData(data)
    })
  }

  // 跳转到编辑
  const toDetail = rowData => () => {
    if(rowData) {
      router.push({
      pathname: '/eContract/businessConfig/detail',
      query: {
        id: rowData.contractBusinessId,
      },
    });
      return
    }
  }

  /**
   *
   *
   * @param {*} props
   * @returns
   */

  const columns = [
    {
      title: '合同标题',
      dataIndex: 'contractTemplateName',
      key: 'contractTemplateName',
      align: 'center',
      render:  (x, row) => <Navigate onClick={toDetail(row)}>{row.contractTemplateName}</Navigate>,
    },
    {
      title: '关联业务类型',
      dataIndex: 'targetType',
      key: 'targetType',
      align: 'center',
      render: (x, row) => <><span>{row.targetType === 'raise' ? '房源认筹' : ''}</span></>
    },
    {
      title: '关联业务标题',
      dataIndex: 'targetName',
      key: 'targetName',
      align: 'center',
    },
    {
      title: '甲方',
      dataIndex: 'companyName',
      key: 'companyName',
      align: 'center',
    },
    {
      title: '发布状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      render: (text, records) => {
        if (records.status === 1) { return '是' }
        if (records.status === 0) { return '否' }
      },
    },
    {
      title: '新增时间',
      dataIndex: 'createDate',
      key: 'createDate',
      align: 'center',
      render: (x, row) => <><span>{`${moment(row.createDate).format('YYYY-MM-DD HH:mm:ss')}`}</span></>
    },
    {
      title: '修改时间',
      dataIndex: 'updateDate',
      key: 'updateDate',
      align: 'center',
      render: (x, row) => <><span>{`${moment(row.updateDate).format('YYYY-MM-DD HH:mm:ss')}`}</span></>
    },
    {
      title: '操作',
      dataIndex: 'handle',
      key: 'handle',
      align: 'center',
      render: withActions((text, record) => [
        <AuthButton name="admin.eContractBusiness.detail.get" noRight={null}>
           <EditIcon text="查看详情" type="look" onClick={toDetail(record)} />
          {/* <a style={{ color: '#66B3FF' }} onClick={toDetail(record)} >查看详情</a> */}
        </AuthButton>,
      ])
    },
  ];
  
  const rowSelection = {
    selectedRowKeys: contractBusinessIndexList,
    onChange: (selectedRowKeys, selectedRows) => {
      setContractBusinessList(selectedRows)
      setContractBusinessIndexList(selectedRowKeys)
    },
  };

  const changePageNum = pageNumber => {
    getList({ pageNum: pageNumber, pageSize: 10, ...props.form.getFieldsValue() })
  }

  // 提交事件
  const handleSubmit = (e, props) => {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      if (!err) {
        getList({ pageNum: 1, pageSize: 10, ...values })
      }
    });
  }

  //重置搜索
  function handleReset () {
    props.form.resetFields();
    getList({ pageNum: 1, pageSize: 10 })
  }

  function showBatchDel(e){
  
    if (demandIds.length <= 0){
      message.info("请选择数据");
      return;
    }
    setBatchDel(e);
    if(!e.visable){
      getList()
    }
  }

  function batchDelTaContractBusiness(){
    console.log(contractBusinessList)
    if (contractBusinessList.length <= 0){
      message.info('请至少选择一条数据')
      return;
    }
    Modal.confirm({
      title: '确认将所选的' + contractBusinessList.length + '条业务配置删除？',
      okText: '确认',
      cancelText: '取消',
      onOk () {
        request({ ...apis.taEcontract.batchDelTaContractBusiness, data: {contractBusinessList} }).then((data) => {
          message.info('操作成功！')
          setContractBusinessIndexList([])
          getList({ pageNum: 1, pageSize: 10 })
        }).catch((err) => {
          console.log('111111', err)
        })
      }
    });
  }

  function addContractManage(){
    router.push({
      pathname: '/eContract/businessConfig/add',
    });
  }

  const { getFieldDecorator } = props.form
  return (

    <>
      <Form layout="inline" onSubmit={e => handleSubmit(e, props)}>
        <Form.Item>
          {getFieldDecorator('contractName')(
            <Input
            prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
            placeholder="合同标题"
          />,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('targetType')(
            <Select style={{ width: '180px' }} placeholder="业务类型">
                <option value="">全部</option>
                <option value="raise">房源认筹</option>
            </Select>
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('targetName')(
            <Input
              prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
              placeholder="业务标题"
            />,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('companyName')(
            <Input
              prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
              placeholder="甲方"
            />,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('status')(
            <Select style={{ width: '180px' }} placeholder="发布状态">
                <option value="">全部</option>
                <option value='1'>是</option>
                <option value='0'>否</option>
            </Select>
          )}
        </Form.Item>
        
        <Form.Item>
            <AuthButton name="admin.taShareActivity.search" noRight={null}>
                <Button type="primary" htmlType="submit" className={styles.searchBtn}>
                    搜索
                </Button>
            </AuthButton>
            <AuthButton name="admin.taShareActivity.search" noRight={null}>
                <Button style={{ marginLeft: 8 }} onClick={handleReset}>
                        重置
                </Button>
            </AuthButton>
        </Form.Item>
      </Form>
      <AuthButton name="admin.eContractBusiness.add.post" noRight={null}>
        <Button type="danger" onClick={() => addContractManage()} className={styles.addBtn}>新增</Button>
      </AuthButton>
      <AuthButton name="admin.eContractBusiness.del" noRight={null}>
        <Button type="primary" onClick={() => batchDelTaContractBusiness()} className={styles.addBtn} style={{marginLeft:'30px'}}>删除</Button>
      </AuthButton>
      <Table rowSelection={rowSelection}
        style={{marginTop:'30px'}} dataSource={data.records} columns={columns} pagination={false} rowKey="activityList" />
      <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '30px' }}>
        <Pagination showQuickJumper defaultCurrent={1} total={data.total} onChange={changePageNum} current={data.current} />
      </div>
    </>
  )
}
const WrappedHeader = Form.create({ name: 'header' })(header);

export default WrappedHeader
