import React, { useState, useEffect } from 'react';
import { Input, Menu, Dropdown, Button, Icon, message, Table, Divider, Tag, Select, Form, Alert, Tabs, Row, Col, Radio, tab, Avatar, Modal, Pagination } from 'antd';
import { FormattedMessage } from 'umi-plugin-react/locale';
import XForm, { FieldTypes } from '../../../../components/XForm';
import router from 'umi/router';
import apis from '../../../../services/apis';
import request from '../../../../utils/request';
import Wangedit from '../../../../components/Wangedit/Wangedit'
import moment from 'moment';
import AddSeal from './AddSeal';
import UpdateSeal from './UpdateSeal';

const { TabPane } = Tabs;

const header = props => {
    const companyId = props.companyId;
  
    const [ data, setData ] = useState({})
    const [sealData, setSealData] = useState({})
    const [sealInfo, setSealInfo] = useState({visable: false, companyId: ''})
    const [updateSeal, setUpdateSeal] = useState({visable: false, companyId: '', sealId: ''})

    useEffect(() => {
      getCompanyData({companyId: companyId});
    },[])
  
    // 查询列表
    function getCompanyData(params) {
      request({ ...apis.seal.listByCompanyId, params: { ...params } }).then((data) => {
        setData(data)
      }).catch((err) => {
        message.error(err.msg || err.message)
      })
    }  

    const changePageNum = (pageNumber) => {
      let values  = props.form.getFieldsValue()
      getCompanyData({ pageNum: pageNumber, pageSize: 10, ...values, companyId: companyId })
    }

    const openFddUrl = () => {
      window.open(data.certifiedAddress)
    }
  
    // 提交事件
    const handleSubmit = e => {
      e.preventDefault();
      props.form.validateFields((err, values) => {
        if (!err) {
          getCompanyData({ pageNumber: 1, pageSize: 10, ...values, companyId: companyId })
        }
      });
    }

     // 重置搜索
     function handleReset () {
      props.form.resetFields();
      getCompanyData({companyId: companyId});
    }

    function back(){
      router.go(-1)
    }
    function addSealInfo(){
      setSealInfo({visable: true, companyId: companyId})
    }

    function updateSealInfo(e){
      setUpdateSeal(e);
    }

    function getList(e) {
      setSealInfo(e)
      getCompanyData(e)
    }

    function updateOnSuccess(e) {
      setUpdateSeal(e);
      getCompanyData(e)
    }

    function updateOnCancel(e) {
      console.log(e, 'cancel')
      setUpdateSeal(e);
      // getCompanyData({companyId: e.companyId
    }

    const delSealInfo = (row) => {
      Modal.confirm({
          title: '删除后无法再使用这些章继续签章，不会影响已签署的合同',
          okText: '确定',
          cancelText: '取消',
          onOk() {
              request({ ...apis.seal.delSealById, urlData:{id: row.sealId} }).then((data) => {
                  message.info('操作成功！')
                  getCompanyData({ pageNum: 1, pageSize: 10, companyId: companyId })
              }).catch((err) => {
                  console.log(err)
                  message.info(err.msg || err.message)
              })
          },
        });
    }

    const defaultSeal = (row) => {
      request({ ...apis.seal.setDefaultSealById, urlData:{id: row.sealId} }).then((data) => {
        message.info('操作成功！')
        getCompanyData({ pageNum: 1, pageSize: 10, companyId: companyId })
      }).catch((err) => {
          console.log(err)
          message.info(err.msg || err.message)
      })              
    }
  



    const columns = [
      {
        title: '印章编号',
        dataIndex: 'sealId',
        key: 'sealId',
        align: 'center',
      },
      {
        title: '印章名称',
        dataIndex: 'sealName',
        key: 'sealName',
        align: 'center',
      },
      {
        title: '印章图',
        dataIndex: 'sealImg',
        key: 'sealImg',
        align: 'center',
        render: (_, record) => <Avatar shape="square" style={{color: 'blue',cursor: 'pointer'}} src={record.sealImg} size={64} icon="user" />,
      },
      {
        title: '印章上传时间',
        dataIndex: 'createDate',
        key: 'createDate',
        align: 'center',
        render: (x, row) => <><span>{row.createDate != null ? `${moment(row.createDate).format('YYYY-MM-DD HH:mm:ss')}` : ''}</span></>,
      },
      {
        title: '默认章',
        dataIndex: 'defaultSeal',
        key: 'defaultSeal',
        align: 'center',
        render: (_, record) => <><span>{record.defaultSeal === 1 ? "是":"否"}</span></>,
      },
      {
        title: '操作',
        dataIndex: '',
        key: '',
        align: 'center',
        render: (text, record) => (
            <>
            <a style={{ color: '#66B3FF' }} onClick={() => updateSealInfo({visable:true, companyId: record.companyId, sealId: record.sealId})} ><span>修改</span></a>
            <a style={{ color: '#66B3FF', marginLeft:'20px' }} onClick={() => delSealInfo(record)} ><span>删除</span></a>
            <a style={{ color: '#66B3FF', marginLeft:'20px' }} onClick={() => defaultSeal(record)} ><span>默认章</span></a>
            </>
        ),
      },
    ]

    const { getFieldDecorator } = props.form
    return (
      <>
      <Form layout="inline" onSubmit={e => handleSubmit(e)}>
        <Form.Item>
          {getFieldDecorator('sealName')(
            <Input placeholder="印章名称"/>,
          )}
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" >
            搜索
          </Button>
          <Button style={{ marginLeft: 8 }} onClick={handleReset}>
            重置
            </Button>
        </Form.Item>
      </Form>
        <div style={{marginTop:'20px', marginBottom:'20px'}}>
          <Button type="danger" onClick={() => addSealInfo({visable:true})} >新增</Button>
          <Button style={{marginLeft:'20px'}} onClick={() => back()} >返回</Button>
        </div>
        <AddSeal visible={sealInfo.visable} companyId={sealInfo.companyId} onCancel={e => setSealInfo(e)} onSuccess={e => getList(e)}/>  
        <UpdateSeal visible={updateSeal.visable} sealId={updateSeal.sealId} companyId={updateSeal.companyId} onCancel={e => updateOnCancel(e)} onSuccess={e => updateOnSuccess(e)}/>  
      <Table dataSource={data.records} columns={columns} pagination={false} rowKey="carouseFigureList"/>
      <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '30px' }}>
        <Pagination showQuickJumper defaultCurrent={1} total={data.total} onChange={changePageNum} current={data.current}/>
      </div>
      </>
    )
  }
  
  const WrappedNormalLoginForm = Form.create({ name: 'header' })(header);
  export default WrappedNormalLoginForm