import React, { useState, useRef, useEffect } from 'react';
import { Modal, Col, Input, Form, Row, PageHeader, Button, Spin, Upload } from 'antd';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { proTableValueEnum, returnDictVal } from '@/utils/CommonUtils';
import { getPage, queryEntrust } from './service';
import './styles.less';
import { getDicData, getSessionUserData } from '@/utils/session';

const entrust: React.FC<{}> = () => {
  const modalHeight = window.innerHeight * 96 / 100;
  const formLayout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
  };
  //获取字典
  const getDict: any = getDicData();
  const dictData = JSON.parse(getDict);
  const { TextArea } = Input;
  const FormItem = Form.Item;
  const [form] = Form.useForm();
  //人员信息
  const userData = getSessionUserData();
  //protable actionRef
  const actionRef = useRef<ActionType>();
  //显隐 查看及分派弹窗
  const [checkModal, checkModalSet] = useState<boolean>(false);
  //loading
  const [spin, spinSet] = useState<boolean>(false);
  const [recordId, recordIdSet] = useState<any>('');//单行id
  const [sectionsInfo, sectionsInfoSet] = useState<any>([]);//标段信息
  const [oneAllInfo, oneAllInfoSet] = useState<any>([{}]);//一行查出来的所有数据
  const [files, filesSet] = useState<any>([]);//附件

  //查询分页数据
  const [pageData, pageDataSet] = useState<any>({
    pageNo: 1,
    pageSize: 10
  });

  //委托列表
  const columns: ProColumns<any>[] = [
    { title: '序号', valueType: 'index', width: 60, },
    { title: '委托方', dataIndex: 'purchaser', width: '15%', search: false },
    { title: '项目名称', dataIndex: 'projectName', width: 400, },
    { title: '方案编号', dataIndex: 'projectNumber', width: '6%', search: false },
    { title: '接收时间', dataIndex: 'receiveTime', width: '10%', valueType: 'dateTime', search: false },
    { title: '撤回时间', dataIndex: 'createDate', width: '10%', valueType: 'dateTime', search: false },
    { title: '采购方式', dataIndex: 'procurementMode', width: '6%', valueEnum: proTableValueEnum(dictData['procurement_mode=entrust']) },
    { title: '标的类型', dataIndex: 'procurementType', width: '5%', search: false, valueEnum: proTableValueEnum(dictData['procurement_type=entrust']) },
    {
      title: '操作', width: '4%',
      valueType: 'option',
      render: (_, record) => {
        return <Button type='text' onClick={() => recordIdSet(record.id)}>查看</Button>
      }
    },
  ];
  //物资清单
  const columnsWz: ProColumns<any>[] = [
    { title: '需求单名称', dataIndex: 'requName', key: 'requName', },
    { title: '需求单编号', dataIndex: 'requNo', key: 'requNo', },
    { title: '物料说明', dataIndex: 'materialDesc', key: 'materialDesc', },
    { title: '本次采购数量', dataIndex: 'num', key: 'num', },
    { title: '单位', dataIndex: 'unit', key: 'unit', },
  ];
  //询价商品
  const columnsXunJiaGood: ProColumns<any>[] = [
    { title: '物料编码', dataIndex: 'itemNumber', },
    { title: '物料名称', dataIndex: 'itemDescription', },
    { title: '商品分类', dataIndex: 'categoryName', },
    // { title: '属性', dataIndex: '', },
    { title: '品牌名称', dataIndex: 'brandName', },
    { title: '物料描述', dataIndex: 'note', },
    { title: '数量', dataIndex: 'num', },
    { title: '单位', dataIndex: 'unit', },
    { title: '基准价', dataIndex: 'standardPrice', },
    { title: '权重占比', dataIndex: 'weightRatio', },
  ];
  //供应商
  const columnsGys: ProColumns<any>[] = [
    { title: '供应商名称', dataIndex: 'suppName', key: 'suppName', },
    { title: '联系人', dataIndex: 'suppLinkManName', key: 'suppLinkManName', },
    { title: '联系人邮箱', dataIndex: 'suppLinkManEmail', key: 'suppLinkManEmail', },
  ];
  //查询委托信息
  useEffect(() => {
    if (recordId != '') {
      getEntrustInfo();
    }
  }, [recordId]);
  async function getEntrustInfo() {
    spinSet(true);
    form.resetFields();
    await queryEntrust({ id: recordId }).then((res) => {
      const data = res.data;
      let filesList: any[] = [];//附件
      if (data != undefined) {
        let ssxm = data.projectEntrustExpand.purpImplementSendVO;//实施项目信息
        if (data.procurementMode === 'procurement_mode_7') {//询价委托
          const inquiry = data.projectEntrustExpand.inquiry
          form.setFieldsValue({
            ...inquiry,
            inquiryModel: inquiry.inquiryModel == 0 ? '公开询价' : inquiry.inquiryModel == 1 ? '定向询价' : '',//询价模式
            bidType: inquiry.bidType == 1 ? '货物' : inquiry.bidType == 2 ? '服务' : inquiry.bidType == 3 ? '施工服务' : '',
            projectManagerName: data.projectManagerName,
            projectManagerPhone: data.projectManagerPhone,
            projectName: data.projectName,//项目名称
            selectType: inquiry.selectType == 0 ? '综合评分法' : inquiry.selectType == 1 ? '最低价法' : '',//中选原则
            delegationName: inquiry.delegationName,//代理机构名称
            cgfs: '公开询价',
          });
          inquiry.attachmentList.map((item: any) => {
            let one = {};
            one['uid'] = item.fileId;
            one['name'] = item.fileName;
            one['url'] = '/api/core-service-ebtp-updownload/v1/attachment/download/oid/' + item.fileId;
            filesList.push(one);
          });
        } else {
          form.setFieldsValue({
            ...data,
            organization: returnDictVal(dictData['organization=entrust'], data.organization),
            sxmmc: ssxm.purpImplementName,
            sxmbh: ssxm.purpImplementNo,
            sxmid: ssxm.id,
            procurementMode: returnDictVal(dictData['procurement_mode=entrust'], data.procurementMode,),
            fxmmc: ssxm.purpSuperVo.purpSuperName,
            fxmbh: ssxm.purpSuperVo.purpSuperNo,
            fxmid: ssxm.purpSuperVo.id,
            businessType: returnDictVal(dictData['bid_method_sub=record'], ssxm.purpSuperVo.businessType,),
          });
          if (ssxm.purpBaseInfoVoList != undefined) {
            sectionsInfoSet(ssxm);
          }
        }

      }
      oneAllInfoSet(data);
      filesSet(filesList);
      checkModalSet(true);
    });
    spinSet(false);
  }
  function reset() {//重置数据
    sectionsInfoSet([]);
    oneAllInfoSet([]);
    recordIdSet('');
    form.resetFields();
  }
  //查看及委托
  const checkChild = () => {//查看页面
    return (
      <>
        <Form {...formLayout} form={form}>
          <h3 className="first-title">分派信息</h3>
          <Row>
            <Col span={12}>
              <FormItem
                name="projectManagerName"
                label="项目经理"
              >
                <Input style={{ width: 300 }} readOnly bordered={false} />
              </FormItem>
            </Col>
            <Col span={12}>
              <FormItem
                name="projectManagerPhone"
                label="联系电话"
              >
                <Input style={{ width: 300 }} readOnly bordered={false} />
              </FormItem>
            </Col>
          </Row>
          {//非询价项目
            oneAllInfo.procurementMode !== 'procurement_mode_7' ?
              returnProInfo()
              : null
          }
          {//询价项目
            oneAllInfo.procurementMode === 'procurement_mode_7' ?
              returnXunJiaProInfo()
              : null
          }
        </Form>
      </>
    )
  }
  function returnProInfo() {//返回 非询价项目 委托项目信息
    return (
      <>
        <h3 className="first-title">委托项目信息</h3>
        <Row>
          {returnCol("purchaser", "purchaser", "委托方")}
          {returnCol("organization", "organization", "组织方式")}
        </Row>
        <Row>
          {returnColArea("entrustDepartment", "entrustDepartment", "委托部门ID")}
          {returnColArea("entrustDepartmentName", "entrustDepartmentName", "采购实施部门")}
        </Row>
        <Row>
          {returnColArea("agencyCompanyName", "agencyCompanyName", "代理公司")}
          {returnColArea("sxmmc", "sxmmc", "采购实施项目名称")}
        </Row>
        <Row>
          {returnCol("sxmbh", "sxmbh", "采购实施项目编号")}
          {returnCol("sxmid", "sxmid", "采购实施项目ID")}
        </Row>
        <Row>
          {returnCol("purchasingManagerName", "purchasingManagerName", "采购经理")}
          {returnCol("purchasingManagerPhone", "purchasingManagerPhone", "采购经理电话")}
        </Row>
        <Row>
          {returnCol("procurementMode", "procurementMode", "采购方式")}
          {returnColArea("fxmmc", "fxmmc", "父项目名称")}
        </Row>
        <Row>
          {returnCol("fxmbh", "fxmbh", "父项目编号")}
          {returnCol("fxmid", "fxmid", "父项目ID")}
        </Row>
        <Row>
          {returnCol("businessType", "businessType", "业务类型")}
        </Row>

        {/* {proType == '招标' && sectionsInfo.purpBaseInfoVoList != undefined ? ( */}
        {sectionsInfo.purpBaseInfoVoList != undefined ? (
          sectionsInfo.purpBaseInfoVoList.map((item: any, index: any) => {
            return (
              <>
                <h3 className="first-title">{`标段信息`}</h3>
                <Row>
                  {returnColInit("xmid", `xmid${index}`, "采购项目ID", item.id)}
                  {returnColInit("cgmc", `cgmc${index}`, "采购名称", item.purpName, true)}
                </Row>
                <Row>
                  {returnColInit("fabh", `fabh${index}`, "采购编号", item.purpNo)}
                  {returnColInit("faid", `faid${index}`, "方案ID", item.projBaseInfoVO.id)}
                </Row>
                <Row>
                  {returnColInit("purpContext", `purpContext${index}`, "项目背景", item.purpContext, true)}
                  {returnColInit("organName", `organName${index}`, "机构名称", item.organName)}
                </Row>
                <Row>
                  {returnColInit("bys", `bys${index}`, "预算金额(元)(不含税)", item.budgetAmount)}
                  {returnColInit("cglx", `cglx${index}`, "标的类型", returnDictVal(dictData['ebp_target_type=ebp_project'], item.projBaseInfoVO.targetType))}
                </Row>
                <Row>
                  {returnColInit("psbf", `psbf${index}`, "评审方法", item.projBaseInfoVO.reviewMethod)}
                  {returnColInit("zjly", `zjly${index}`, "资金来源", returnDictVal(dictData['ebp_fund_orign=ebp_project'], item.projBaseInfoVO.fundOrign))}
                </Row>
                <Row>
                  {/* {returnColInit("suborProvince", `suborProvince${index}`, "所属省分", item.suborProvince)} */}

                  <Col span={12}><FormItem
                    name="systemLogo"
                    label="附件"
                  >
                    {
                      item.projBaseInfoVO?.baseFileNoPageVOList?.length > 0 ?
                        <>
                          {fileback(item.projBaseInfoVO?.baseFileNoPageVOList)}
                        </>
                        : '无附件'
                    }
                  </FormItem></Col>
                </Row>
                <h3 className="scd-title">物资清单</h3>
                <ProTable columns={columnsWz} dataSource={item.purpMaterialVOList} search={false} options={false} />
                <h3 className="scd-title">供应商(请以实际报名供应商为准)</h3>
                <ProTable columns={columnsGys} dataSource={item.projBaseInfoVO.projSuppRelVOList} search={false} options={false} />
              </>
            )
          })
        ) : null}
      </>
    )
  }
  function returnXunJiaProInfo() {//返回 询价项目 委托项目信息
    return (
      <>
        <h3 className="first-title">委托项目信息</h3>
        <Row>
          {returnCol("inquiryNo", "inquiryNo", "询价单号")}
          {returnCol("managerCn", "managerCn", "询价人姓名")}
        </Row>
        <Row>
          {returnCol("inquiryOrg", "inquiryOrg", "询价单位名称")}
          {returnCol("inquiryModel", "inquiryModel", "询价模式")}
        </Row>
        <Row>
          {returnCol("projectName", "projectName", "项目名称")}
          {returnCol("cgfs", "cgfs", "采购方式")}
        </Row>
        <Row>
          {returnCol("delegationName", "delegationName", "代理机构名称")}
          {returnCol("selectType", "selectType", "中选原则")}
        </Row>
        <Row>
          {returnCol("bidType", "bidType", "标的类型")}
        </Row>
        <Row>
          <Col span={12}><FormItem
            name="systemLogo"
            label="附件"
          >
            {
              files.length > 0 ? <Upload key='uploadInquiry' fileList={files} showUploadList={{ showRemoveIcon: false }} /> : '无附件'
            }
          </FormItem></Col>
        </Row>
        <h3 className="scd-title">物资清单</h3>
        <ProTable columns={columnsXunJiaGood} dataSource={oneAllInfo?.projectEntrustExpand?.inquiry?.inquiryGoodsList} search={false} options={false} />
      </>
    )
  }

  //附件
  function fileback(data: any) {
    let fileList: any[] = [];
    data.map((item: any) => {
      let one = {}
      one['uid'] = item.documentCenterFileId;
      one['name'] = item.originalName;
      one['url'] = '/api/core-service-ebtp-updownload/v1/attachment/download/oid/' + item.documentCenterFileId;
      fileList.push(one);
    })
    return <Upload key='upload' fileList={fileList} showUploadList={{ showRemoveIcon: false }} />
  }
  //返回col
  const returnCol = (key: any, name: any, label: any) => {
    return (
      <Col span={12}><FormItem
        key={key}
        name={name}
        label={label}
      >
        <Input bordered={false} readOnly />
      </FormItem></Col>
    )
  }
  //返回col area
  const returnColArea = (key: any, name: any, label: any) => {
    return (
      <Col span={12}><FormItem
        key={key}
        name={name}
        label={label}
      >
        <TextArea bordered={false} readOnly autoSize />
      </FormItem></Col>
    )
  }
  //返回col并赋值
  const returnColInit = (key: any, name: any, label: any, init: any, area?: boolean) => {
    return (
      <Col span={12}><FormItem
        key={key}
        name={name}
        label={label}
        initialValue={init}
      >
        {
          area ? <TextArea bordered={false} readOnly autoSize /> : <Input bordered={false} readOnly />
        }
      </FormItem></Col>
    )
  }
  //查看页脚
  function renderFooter() {
    return (
      <Button type='primary' onClick={() => {
        checkModalSet(false);
        reset()
      }}>关闭</Button>
    )
  }
  return (
    <Spin spinning={spin}>
      <PageHeader title="委托撤回记录" />
      <div style={{ maxHeight: innerHeight - 130, height: innerHeight - 130 }} className='xsy-entrust bgCWhite'>
        <ProTable<any>
          actionRef={actionRef}//action触发后更新表格
          columns={columns}//表格
          options={false}
          bordered={false}
          className='tableSearch'
          size='small'
          search={{ labelWidth: 'auto', span: 6 }}
          request={async (params) => {
            const req = {
              ...params,
              basePageRequest: { pageNo: pageData.pageNo, pageSize: pageData.pageSize },
            }
            if (userData?.roleIds == 'ebtp-purchase') {//采购经理
              req['purchasingManager'] = userData?.userId
            } else if (userData?.roleIds == 'ebtp-agency-admin') {//代理机构业务管理员
              req['agencyCompany'] = userData?.organizationId
            } else if (userData?.roleIds == 'ebtp-agency-project-manager') {//代理机构业务经理 项目经理
              req['projectManager'] = userData?.userId
            } else {
              return []
            }
            const res = await getPage(req);
            const result = {
              data: res.data.records,
              total: res.data.total,
              success: res.success,
              pageSize: res.data.size,
              current: res.data.current
            };
            return result;
          }}
          pagination={{
            defaultPageSize: 10,
            showSizeChanger: false,
            onChange: (page, pageSize) => pageDataSet({ pageNo: page, pageSize: pageSize }),
            onShowSizeChange: (current, size) => pageDataSet({ pageNo: current, pageSize: size }),
          }}
          onReset={() => { pageDataSet({ pageNo: 1, pageSize: 10 }) }}
        />
      </div>
      {/* 查看 */}
      <Modal
        visible={checkModal}
        destroyOnClose
        style={{ maxHeight: modalHeight }}
        bodyStyle={{ maxHeight: modalHeight - 108, overflowY: 'auto', }}
        width={'1000px'}
        centered
        title="委托信息"
        onCancel={() => {
          checkModalSet(false);
          reset();
        }}
        footer={renderFooter()}
      >
        {checkChild()}
      </Modal >
    </Spin >
  )
};
export default entrust;