/**
 * @author  Xyz
 * 分公司管理
 */
import React from 'react';
import { connect } from 'dva';
import {
  Form,
  Input,
  Button,
  message,
  Table,
  Popover,
  Modal,
  Tabs,
  Alert
} from 'antd';
const store = require('store');
import { Container, SearchItem, Options } from './styles';
import PTable from '../../../components/Pro/PTable';
import PDrawer from '../../../components/Pro/PDrawer';

import {
  systemComVaseInfoGet,
  getRegionMenuButton
} from '../../../services/api';

import { AddCompanyTip } from './components';
import DrawBranchCompanyDetail from './DrawBranchCompanyDetail'; //新增分公司
import DrawChildCompanyBasic from './DrawChildCompanyBasic';//分公司基础信息
import DrawChildCompanyIdentification from './DrawChildCompanyIdentification'; //分公司详情
const FormItem = Form.Item;
const { TabPane } = Tabs;
@Form.create()
@connect(state => ({
  menuInfo: state.global.menuInfo,
}))
export default class BranchCompanyManager extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      visible: false,
      isBasicOpen: false, //是否显示分公司详情
      isIdentificationOpen: false,
      pageParm: {
        //数据请求 分页信息
        pageSize: '10', //缴交情况
        pageNumber: '1',
        keyWord: ''
      },
      comBranchId: '', //分公司ID
      forceUpdate: false,
      comId: '',
      btnControl: [],
      modalVisible: false //分公司开通成功后提示
    };
  }

  /******************************生命周期******************************/

  componentDidMount = () => {
    const currentMenu = this.props.menuInfo.find(v => v.menuName == '分公司管理');
    const menuId = currentMenu? currentMenu.menuId: '';
    systemComVaseInfoGet({}).then(res => {
      const regionId = res.data.regProvince;
      getRegionMenuButton({menuId, regionId}).then(respones => {
        this.setState({
          btnControl: respones.data || []
        });
      });
    });
  };

  /******************************ajax请求******************************/

  /******************************相关事件******************************/

  //新增分公司
  addCompany = () => {
    this.setState({ visible: true, comBranchId: '' });
  };
  //修改分公司 item
  upDateItem = ({ comBranchId }) => {
    if (!comBranchId) {
      return;
    }
    this.setState({ visible: true, comBranchId });
  };
  //查看基础信息 item
  basicInfoOpen = (record) => {
    this.setState({
      isBasicOpen: true,
      comId: record["comBranchId"]
    });
  }
  closeBasicDrawer = () => {
    this.setState({isBasicOpen: false});
  }
  //关闭 修改 item 抽屉
  closeDrawer = () => {
    this.setState({ visible: false });
    // Modal.confirm({
    //   title: '当前信息未提交，返回后无法保证。是否确认返回？',
    //   okText: '确定',
    //   cancelText: '取消',
    //   onOk: () => {
    //     this.setState({ visible: false });
    //   },
    //   onCancel: () => {
    //     console.log('Cancel');
    //   },
    // });
  };
  confirDrawer = () => {
    this.setState({ visible: false });
  };
  handleOk = () => {
    this.setState({
      modalVisible: false
    });
  }
  //删除提示框
  deleteConfirm = () => {
    Modal.confirm({
      title: '删除后将无法查看分公司信息，并影响年报统计。是否确认删除？',
      okText: '确定',
      cancelText: '取消'
    });
  };
  //搜索
  search = () => {
    this.setState({ forceUpdate: true }, () => {
      this.setState({ forceUpdate: false });
    });
  };

  //重置搜索条件
  resetSearch = () => {
    const pageParm = {
      pageSize: '10',
      pageNumber: '1',
      keyWord: ''
    };
    this.setState({ pageParm });
  };

  //关键字更改
  inputChange = e => {
    const pageParm = this.state.pageParm;
    pageParm.keyWord = e.target.value;
    this.setState({ pageParm });
  };

  //查看认证信息
  indetificationOpen = record => {
    this.setState({
      isIdentificationOpen: true,
      comId: record['comBranchId']
    });
  };

  closeIdentDrawer = () => {
    this.setState({ isIdentificationOpen: false });
  };

  /******************************render******************************/
  renderTable = () => {
    const columns1 = [
      {
        title: '分公司名称',
        dataIndex: 'comName',
        key: 'comName',
        // render: text => <a href="javascript:;">{text}</a>,
        render: (text, record) => (
          <div>
            {record.comName ? <span>{record.comName}</span> : <span>-</span>}
          </div>
        )
      },
      {
        title: '统一社会信用代码',
        dataIndex: 'comCerNo',
        key: 'comCerNo',
        render: (text, record) => (
          <div>
            {record.comCerNo ? <span>{record.comCerNo}</span> : <span>-</span>}
          </div>
        )
      },
      {
        title: '负责人',
        dataIndex: 'legalRepName',
        key: 'legalRepName',
        render: (text, record) => (
          <div>
            {record.legalRepName ? (
              <span>{record.legalRepName}</span>
            ) : (
              <span>-</span>
            )}
          </div>
        )
      },
      {
        title: '负责人手机',
        dataIndex: 'legalRepPhone',
        key: 'legalRepPhone',
        render: (text, record) => (
          <div>
            {record.legalRepPhone ? (
              <span>{record.legalRepPhone}</span>
            ) : (
              <span>-</span>
            )}
          </div>
        )
      },
      {
        title: '注册地址',
        dataIndex: 'regAddress',
        key: 'regAddress',
        render: (text, { regProvinceName, regCityName, regAreaName }) => (
          <span>{regProvinceName + '-' + regCityName + '-' + regAreaName}</span>
        )
      },
      {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <Options>
            {/* <span onClick={this.upDateItem.bind(this, record)}>基础信息</span> */}
            <span onClick={this.basicInfoOpen.bind(this, record)}>基础信息</span>
            <span onClick={this.indetificationOpen.bind(this, record)}>
              认证信息
            </span>
            {/* <span onClick={this.upDateItem.bind(this, record)}>修改</span> */}
            {/* <span onClick={this.deleteConfirm}>删除</span> */}
            {/* <span>管理层</span> */}
          </Options>
        )
      }
    ];

    return (
      <PTable
        url='enterpriseCompanyComBaseInfoGetBranch'
        pageParm={this.state.pageParm}
        columns={columns1}
        forceUpdate={this.state.forceUpdate}
      />
    );
  };

  render() {
    const { visible, comBranchId, isIdentificationOpen, isBasicOpen } = this.state;
    return (
      <Container>
        <Tabs defaultActiveKey='1'>
          <TabPane tab='分公司管理' key='1'>
            <Alert
              message='分公司独立注册并填写总公司信息后，自动关联到当前企业。如有疑问请联系客服：400-662-9696。'
              type='warning'
              style={{ marginBottom: 16 }}
              showIcon
            />
            <SearchItem>
              关键字：
              <Input
                className='input'
                placeholder='请输入法定负责人/手机号'
                onChange={this.inputChange}
                value={this.state.pageParm.keyWord}
              />
              <Button className='btn' type='primary' onClick={this.search}>
                搜索
              </Button>
              <Button onClick={this.resetSearch}>重置</Button>
            </SearchItem>
            <SearchItem>
              {
                this.state.btnControl.map(item => {
                  return (
                    <Button 
                    className="btn"
                    style={
                      {
                        display: item.isActive == 1? 'block': 'none'
                      }
                    } 
                    // type={item.buttonName==='新增分公司'? 'primary': ''} 
                    type={(() => {
                      switch(item.buttonName) {
                        case '新增分公司':
                          return 'primary';
                        case '在线备案':
                          return 'danger';
                      }
                    })()} 
                    onClick={(() => {
                      switch (item.buttonName) {
                        case '新增分公司':
                          return this.addCompany;
                        case '在线备案':
                          return (() => {
                            // window.history.go(0);
                            /*** 点击按钮跳转 备案许可申报 页面。*/
                            this.props.history.push('/PoliceDeclare/DeclarationList');
                          });
                      }
                    })()}
                  
                      // onClick={this.addCompany}
                    >
                    {item.buttonName}
                    </Button>
                  );
                })
              }

            {/* <Button
                type='danger'
                onClick={() => {
                  this.props.history.push('/PoliceDeclare/DeclarationList');
                }}
              >
                在线备案
              </Button> */}

              {/* <Popover content={AddCompanyTip} trigger="hover" placement="topLeft">
                <Button className="btn" type="primary" onClick={this.addCompany}>+新增分公司</Button>
              </Popover> */}
              
            </SearchItem>

            {this.renderTable()}

            <DrawBranchCompanyDetail
              visible={visible}
              comBranchId={comBranchId}
              closeDrawer={this.closeDrawer}
              confirDrawer={this.confirDrawer}
              updataTable={this.search}
              success={() => {
                this.setState({
                  modalVisible: true
                });
              }}
            />
            <DrawChildCompanyIdentification
              visible={isIdentificationOpen}
              closeDrawer={this.closeIdentDrawer}
              comId={this.state.comId}
            />
            <DrawChildCompanyBasic
                visible={isBasicOpen}
                closeDrawer={this.closeBasicDrawer}
                comId={this.state.comId}
              />
          </TabPane>
        </Tabs>
        <Modal
              title='分公司开通成功'
              visible={this.state.modalVisible}
              onOk={this.handleOk}
              className="update_modal"
            >
              <div>
                  系统已向负责人手机号发送开通短信，请提醒其注意查收并登陆系统完成初始化
              </div>
            </Modal>
      </Container>
    );
  }
}
