import React, { useState, useRef, } from 'react';
import { Button, Tabs, Form, Input, Modal, Checkbox, message, PageHeader, Popconfirm, Progress, Spin } from 'antd';
import ProTable, { ActionType, ProColumns } from '@ant-design/pro-table';
import { getSection, exitProject, getProject, getOther, supplierRegister, exitProjectPayCheck } from './service';
import { getSupplierUser } from '@/utils/SupplierList/service'
import { getProMethod, } from '@/utils/session';
import '@/assets/ld_style.less';
import { history } from 'umi';
import { followUpAProjectSupplier, getDicData } from '@/utils/session';
import { getDictName, getProjectTypeCode, getURLInformation, getUrlParam, getUrlRelativePath, isEmpty, isNotEmpty, proTableValueEnum, proTableValueEnumOther } from '@/utils/CommonUtils';
import { btnAuthority } from '@/utils/authority';
import kefu from '@/assets/img/kefu.png'  //智慧客服
import {submitHiddenForm, createHiddenForm} from '@/utils/CustomerService' //智慧客服

const { TabPane } = Tabs;
const { TextArea } = Input;
const CheckboxGroup = Checkbox.Group;

const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14 },
};

const plainOptions: any[] = [];
const defaultCheckedList: any[] = [];

const Index: React.FC<{}> = () => {
  const { confirm } = Modal;
  const checkRelationRef = useRef<ActionType>(); //操作数据后刷新列表
  const [personList, setPersonList] = useState<any>([]); // 负责人列表
  const [plainList, setPlainList] = useState(plainOptions); // 选择标段
  const [quitVisible, setQuitVisible] = useState<boolean>(false); // 退出项目弹窗按钮
  const [personVisible, setPersonVisible] = useState<boolean>(false); // 修改负责人弹窗按钮
  const [indeterminate, setIndeterminate] = useState<boolean>(false); // 复选框全选
  const [checkAll, setCheckAll] = useState<boolean>(false); // 复选框全选
  const [checkedList, setCheckedList] = useState(defaultCheckedList); // 全选选中数组
  const [sectionsVal, setSectionsVal] = useState<any>([]); // 选中数组id
  const [organId, setOrganId] = useState<any>(); // id
  const [projectId, setProjectId] = useState<any>(); // id


  const [quitForm] = Form.useForm();
  const MethodDict = getProMethod(); //获取采购方式
  const modalHeight = (innerHeight * 96) / 100;
  //招募方式
  const recruitmentMethodRecord = 'recruitment_method=record';

  //存储当前页面项目类型
  let proTypeCode = getProjectTypeCode();
  // 项目列表url
  const [projectParams, setProjectParams] = useState<string>("");
  const projectName = getUrlParam("projectName");
  const bidMethodDict = getURLInformation("bidMethodDict");
  const current = getURLInformation("current");

  //获取字典
  const getDict: any = getDicData();
  const dictData = JSON.parse(getDict);

  const actionRef = useRef<ActionType>();
  const personColumns: ProColumns<{}>[] = [  // 修改项目负责人
    {
      title: '姓名',
      dataIndex: 'empName',
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      search: false,
    },
    {
      title: '账号',
      dataIndex: 'userAccount',
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'action',
      search: false,
      align: 'center',
      render: (text: any, record: any) => (
        <Popconfirm
          title="您确定要修改负责人吗?"
          onConfirm={() => choosePerson(record)}
          okText="确定"
          cancelText="返回"
        >
          <Button type="link" danger size="middle">选择</Button>
        </Popconfirm>
      ),
    },
  ];
  const columns: any = [  // 我参与的项目
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      search: false,
      width: 50,
    },
    {
      title: proTypeCode.indexOf("procurement_mode_4") !== -1 ? '招募方式' : '采购方式',
      dataIndex: 'bidMethodDict',
      search: proTypeCode?.length > 1 ? null : false,
      initialValue: bidMethodDict ? bidMethodDict : void 0,
      valueEnum: proTableValueEnumOther(dictData['procurement_mode=entrust'], proTypeCode),
      width: '7%',
      render: (_: any, record: any) => {
        if (proTypeCode.indexOf("procurement_mode_4") !== -1) {
          const recruitmentMethod = getDictName(dictData[recruitmentMethodRecord], record.examinationMethodDict)
          if (recruitmentMethod == '一次评审') {
            return "公开招募"
          } else {
            return "公开招募(多轮评审)"
          }
        } else {
          return _
        }
      }
    },
    {
      title: '项目名称',
      dataIndex: 'projectName',
      initialValue: projectName ? projectName : void 0,
    },
    {
      title: '我要咨询',
      dataIndex: 'consult',
      render: (text: any, record: any) => (
        <span onClick={()=>{saveTmpForm(record); initChatUI()}}><img style={{width:20,height:20, cursor:'pointer'}} src={kefu} alt="" /></span>
      ),
    },
    {
      title: proTypeCode.indexOf("procurement_mode_4") !== -1 ? '招募人' : '采购人',
      dataIndex: 'tendereeOrgName',
      search: false,
      width: '15%'
    },
    {
      title: '代理机构',
      dataIndex: 'tenderAgencyName',
      search: false,
      width: '15%'
    },
    {
      title: '项目分类',
      dataIndex: 'procurementType',
      valueEnum: proTableValueEnum(dictData['procurement_type=entrust']),
      search: false,
      width: '5%'
    },
    {
      title: '所属区域',
      dataIndex: 'regionDictName',
      search: false,
      width: '15%'
    },
    {
      title: '操作',
      width: '7%',
      search: false,
      render: (text: any, record: any) => {
        if (MethodDict == "procurement_mode_7") {
          return (
            <Button type="text" onClick={() => saveProject(record)} danger>项目跟进</Button>
          )
        } else {
          return (
            <>
              <Button hidden={btnAuthority(['ebtp-supplier'])} type="text" onClick={() => saveProject(record)} danger>项目跟进</Button>
              <Button hidden={btnAuthority(['ebtp-supplier'])} type="text" danger onClick={() => changePerson(record)} >修改负责人</Button>
              <Button hidden={btnAuthority(['ebtp-supplier'])} type="text" danger onClick={() => quitProject(record.id)} >退出项目</Button>
            </>
          )
        }
      }
    },
  ];
  const otherColumns: any[] = [  // 公司其他项目
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      search: false,
      width: 50,
    },
    {
      title: '项目名称',
      dataIndex: 'projectName',
    },
    {
      title: '采购类型',
      dataIndex: 'procurementTypeDict',
      search: false,
      width: '5%',
      valueEnum: proTableValueEnum(dictData['procurement_type=entrust'])
    },
    {
      title: '采购方式',
      dataIndex: 'bidMethodDict',
      search: false,
      width: '7%',
      valueEnum: proTableValueEnum(dictData['procurement_mode=entrust'])
    },
    {
      title: '已报名标段名称',
      dataIndex: 'bidSectName',
      width: '20%',
      search: false
    },
    {
      title: '已报名标段编号',
      dataIndex: 'bidSectBizNum',
      width: '10%',
      search: false
    },
    {
      title: '项目负责人',
      dataIndex: 'projectBidUser',
      search: false,
      width: '7%'
    },
  ];
  const dataSource = [
    '语雀的天空',
    'Ant Design',
    '蚂蚁金服体验科技',
    'TechUI',
    'TechUI 2.0',
    'Bigfish',
    'Umi',
  ].map((item) => ({
    title: item,
    // subTitle: <Tag color="#5BD8A6">语雀专栏</Tag>,
    actions: [
      <a>邀请</a>,
      <a>操作</a>,
    ],
    avatar: (
      <span className="pro-type">公</span>
    ),
    content: (
      <>
        <div
          style={{
            flex: 1,
          }}
        >
          <span>第一个包</span>
          <span className="ml20">11</span>
          <span
            className="ml20"
            style={{
              width: 200,
              display: "inline-block"
            }}
          >
            <Progress percent={80} />
          </span>
        </div>
        <div
          style={{
            flex: 1,
            marginTop: 8,
          }}
        >
          <span>第一个包</span>
          <span className="ml20">11</span>
          <span
            className="ml20"
            style={{
              width: 200,
              display: "inline-block"
            }}
          >
            <Progress percent={80} />
          </span>
        </div>
      </>
    ),
  }));

  /**
   * 获取返回路径
   * @returns 
   */
  const getReturnURL = () => {
    let projectURLParams = JSON.parse(projectParams);
    let params = `${'?current=' + projectURLParams.current}${isEmpty(projectURLParams.projectName) ? '' : '&projectName=' + projectURLParams.projectName}${isEmpty(projectURLParams.bidMethodDict) ? '' : '&bidMethodDict=' + projectURLParams.bidMethodDict}`;
    return getUrlRelativePath() + params;
  }

  const saveProject = async (val: any) => { // 点击项目跟进存储项目信息
    //创建临时表单-智慧客服
    saveTmpForm(val)
    val.returnURL = getReturnURL()
    await followUpAProjectSupplier(val);
    history.push('/ProjectLayout/Supplier/HomePageSectionList')
  }

  const changePerson = (val: any) => { // 修改负责人弹窗
    setPersonVisible(true)
    setOrganId(val.companyId)
    setProjectId(val.id)
  }

  const [spin, spinSet] = useState(false);
  const choosePerson = async (val: any) => { // 确定修改负责人
    spinSet(true);
    let data = {
      bidUserId: val.userAccount,
      bidUserName: val.empName,
      companyId: val.partnerMdmCode,
      projectId: projectId
    }
    await supplierRegister(data).then((res: any) => {
      if (res.code == 200) {
        message.success('修改负责人成功！')
        checkRelationRef.current?.reload();
        setPersonVisible(false)
      }
    });
    spinSet(false);
  }

  const onFinish = (val: any) => { // 校验成功确认提交
    let date = {
      packageIdList: val.checkbox,
      remark: val.reason
    }
    exitProject(date).then((res: any) => {
      if (res.code == 200) {
        setQuitVisible(false)
        message.success('退出成功')
        setCheckedList([])
        setIndeterminate(false)
      } else {
        setQuitVisible(false)
      }
    })
  };

  const onCheckAllChange = (e: any) => { // 全选
    setCheckedList(e.target.checked ? sectionsVal : []);
    setIndeterminate(false)
    setCheckAll(e.target.checked)
  };

  const onChange = (checkedList: any) => { // 多选单点
    setCheckedList(checkedList)
    setIndeterminate(!!checkedList.length && checkedList.length < sectionsVal.length)
    setCheckAll(checkedList.length === sectionsVal.length)
  };

  const quitProject = (id: any) => { // 退出项目
    setQuitVisible(true)
    quitForm.resetFields()
    getSection(id).then((res: any) => {
      let secVals = [];
      if (res.success) {
        secVals = res.data.map((item: any) => { return item.id })
      }
      setPlainList(res.data)
      setSectionsVal(secVals)
    })
  }

  const showConfirm = (date: any) => {
    confirm({
      title: date,
      onOk() {
        if (checkedList.length > 0) {
          //quitForm.getFieldValue().checkbox = checkedList  报错——林杰注释
          quitForm.setFieldsValue({checkbox: checkedList})
        }
        quitForm.submit()
        setCheckAll(false)
        setIndeterminate(false)
        setCheckedList([])
        checkRelationRef.current?.reload();
      },
      onCancel() {
        setCheckAll(false)
        setIndeterminate(false)
        setCheckedList([])
        setQuitVisible(false)
      },
    });
  }

  const submitQuit = (val: any) => { // 确定并进行校验
    exitProjectPayCheck(checkedList).then((res: any) => {
      if(res.data && res.data != null){
        showConfirm(res.data)
      } else {
        if (checkedList.length > 0) {
          //quitForm.getFieldValue().checkbox = checkedList 报错——林杰注释
          quitForm.setFieldsValue({checkbox: checkedList})
        }
        quitForm.submit()
        setCheckAll(false)
        setIndeterminate(false)
        setCheckedList([])
        checkRelationRef.current?.reload();
      }
    })
  }
  const saveTmpForm = (record:any)=>{//智慧客服-创建临时表单
    let roleAuthority: any | null = sessionStorage.getItem('roleAuthority');
    const inputList = [
      {
        label:null,
        paraName:'origin',
        isEncode:false,
        paraVal:'eBid',
      },
      {
        label:'项目名称',
        paraName:'projectName',
        isEncode:true,
        paraVal:record.projectName,
      },
      {
        label:'项目编号',
        paraName:'ebpProjectNumber',
        isEncode:false,
        paraVal:record.ebpProjectNumber,
      },
      {
        label:'项目流水号',
        paraName:'projectBizNum',
        isEncode:false,
        paraVal:record.projectBizNum,
      },
      {
        label:null,
        paraName:'tenderAgencyId',
        isEncode:false,
        paraVal:record.tenderAgencyId,
      },
      {
        label:null,
        paraName:'tenderAgencyName',
        isEncode:true,
        paraVal:record.tenderAgencyName,
      },
      {
        label:'项目状态',
        paraName:'status',
        isEncode:false,
        paraVal:record.status==1?'编辑中':record.status==2?'进行中':record.status==3?'已结束':record.status==9?'废止':'无效状态',
      },
      {
        label:'采购单位',
        paraName:'tendereeName',
        isEncode:true,
        paraVal:record.tendereeName,
      },
      {
        label:'实施单位',
        paraName:'providerName',
        isEncode:true,
        paraVal:record.tenderAgencyName,
      },
      {
        label:'实施人员',
        paraName:'ownerContactName',
        isEncode:true,
        paraVal:record.appManagerName+'-'+record.appManagerId+'-'+record.appManagerTel
      },
      {
        label:null,
        paraName:'roleAuthority',
        isEncode:false,
        paraVal:JSON.parse(roleAuthority)[0],
      },
      {
        label:null,
        paraName:'module',
        isEncode:false,
        paraVal:'10',
      },
      {
        label:null,
        paraName:'custType',
        isEncode:false,
        paraVal:'2',
      },
    ]
    createHiddenForm(inputList, window.location.pathname)
  }
  const initChatUI = ()=>{ //打开客服界面
    submitHiddenForm()
  }
  return (
    <>
      <PageHeader
        title="我参与的项目"
      />
      <div className="bidContent projectsInvolved">
        <Tabs defaultActiveKey="1">
          <TabPane tab="我参与的项目" key="1">

            {/* <ProList<any>
              className="pro-list"
              pagination={{
                defaultPageSize: 10,
                showSizeChanger: true,
              }}
              metas={{
                title: {},
                subTitle: {},
                type: {},
                avatar: {},
                content: {},
                actions: {},
              }}
              dataSource={dataSource}
            /> */}

            <ProTable
              actionRef={checkRelationRef}
              className="proSearch"
              columns={columns}
              params={{ "procurementMode": proTypeCode }}
              size='small'
              request={async (params) =>
                await getProject(params, proTypeCode).then((res) => {
                  setProjectParams(JSON.stringify(params));
                  if (res.code == 200) {
                    let data = res.data;
                    return Promise.resolve({
                      data: data.records,
                      success: res.success,
                      total: res.data.total,
                      current: res.data.current,
                    });
                  }
                  return Promise.resolve({
                    data: [],
                    success: false,
                    total: 0,
                    current: 1,
                  });
                })
              }
              search={{
                filterType: "query",
                optionRender: (searchConfig: any, { form }) => {
                  return [
                    <Button
                      key="resetText"
                      onClick={() => {
                        form?.setFieldsValue({
                          projectName: null,
                          bidMethodDict: null,
                          current: 1,
                        })
                        form?.submit();
                      }}
                    >
                      {searchConfig?.resetText}
                    </Button>,
                    <Button
                      key="searchText"
                      type="primary"
                      onClick={() => {
                        form?.submit();
                      }}
                    >
                      {searchConfig?.searchText}
                    </Button>,
                  ];
                },
              }}
              pagination={{ defaultCurrent: isNotEmpty(current) ? Number(current) : 1, defaultPageSize: 10, showSizeChanger: false }}//默认显示条数
              toolBarRender={false}
            />

            <Modal // 修改负责人
              title="选择负责人"
              width={800}
              visible={personVisible}
              onCancel={() => setPersonVisible(false)}
              footer={[<Button onClick={() => setPersonVisible(false)}>关闭</Button>]}
              centered
              style={{ maxHeight: modalHeight }}
              bodyStyle={{ maxHeight: modalHeight - 107, overflowY: 'auto' }}
            >
              <Spin spinning={spin}>
                <ProTable<any>
                  size='small'
                  actionRef={actionRef}//action触发后更新表格
                  columns={personColumns}
                  request={async (params) =>
                    await getSupplierUser({
                      ...params,
                      partnerMdmCode: organId,
                      pageNum: params.current,
                      pageSize: params.pageSize,
                    }).then((res) => {
                      if (res.success) {
                        let data = res.data;
                        setPersonList(data.records)
                        return Promise.resolve({
                          data: data.records,
                          success: res.success,
                          total: res.data.total,
                          current: res.data.page,
                        });
                      }
                      return Promise.resolve({
                        data: [],
                        success: false,
                        total: 0,
                        current: 1,
                      });
                    })
                  }
                  pagination={{ defaultPageSize: 10, showSizeChanger: false }}//默认显示条数
                  dataSource={personList}
                  toolBarRender={false}
                  bordered
                />
              </Spin>
            </Modal>
            <Modal // 退出项目
              title="退出项目"
              width={800}
              visible={quitVisible}
              onCancel={() => setQuitVisible(false)}
              onOk={submitQuit}
              centered
            >
              <Form
                {...formItemLayout}
                onFinish={onFinish}
                form={quitForm}
              >
                <Form.Item
                  label="退出原因"
                  name="reason"
                  rules={[{ required: true, message: '请输入退出原因' }]}
                >
                  <TextArea maxLength={100} rows={4} />
                </Form.Item>
                <Form.Item
                  name="checkbox"
                  label="选择标段"
                  rules={[{ required: true, message: '请选择标段', type: 'array' }]}
                >
                  <Checkbox
                    indeterminate={indeterminate}
                    onChange={onCheckAllChange}
                    checked={checkAll}
                  >全选</Checkbox>
                  <CheckboxGroup
                    // options={plainList}
                    value={checkedList}
                    onChange={onChange}
                  >
                    {
                      plainList.map((item: any, index: any) => {
                        return (
                          <Checkbox value={item.id} key={index}>{item.bidSectName}</Checkbox>
                        )
                      })
                    }
                  </CheckboxGroup>
                </Form.Item>
              </Form>
            </Modal>
          </TabPane>
          <TabPane tab="公司其他项目" key="2">
            <ProTable
              size='small'
              className="proSearch"
              columns={otherColumns}
              params={{ "procurementMode": proTypeCode }}
              request={async (params) =>
                await getOther(params).then((res) => {
                  if (res.code == 200) {
                    let data = res.data;
                    return Promise.resolve({
                      data: data.records,
                      success: res.success,
                      total: res.data.total,
                      current: res.data.current,
                    });
                  }
                  return Promise.resolve({
                    data: [],
                    success: false,
                    total: 0,
                    current: 1,
                  });
                })
              }
              pagination={{ defaultPageSize: 10, showSizeChanger: false }}//默认显示条数
              toolBarRender={false}
            />
          </TabPane>
        </Tabs>
      </div>
    </>
  )
}
export default Index
