import React, { useEffect, useState } from 'react';
import { Table, Button, Space, Form, Radio, Select, Input, InputNumber, Upload, Row, Col, message, Spin } from 'antd';
import { TableListItem } from './data';
import ExtendUpload from "@/utils/ExtendUpload";
import '@/assets/ld_style.less';
import {findArithmeticError, getList,getRoomType,savePrice} from './service';
import { getProMethod, getRoomId, getSessionRoleData, getSessionUserData } from '@/utils/session';
import ProTable from '@ant-design/pro-table';

const { Option } = Select;
const { TextArea } = Input;

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

function wayValue(key:any){
  let name = "";
  //0-调整价  1-最终价格
  if(key==="0"){
    name = "调整价";
  }else if(key==="1"){
    name = "最终价格";
  }
  return name;
}

function typeValue(key:any){
  let name = "";
  //0-小微、1-缺项、2-单价和总价不一致、3-手动输入
  if(key===0){
    name = "小微";
  }else if(key===1){
    name = "缺项";
  }else if(key===2){
    name = "单价和总价不一致";
  }else if(key===3){
    name = "手动输入";
  }
  return name;
}

const Index: React.FC<{}> = () => {
  let roomId=getRoomId();//sessionStorage.getItem('roomId');//sessionStorage.getItem('roomId')
  var roleId = getSessionUserData().roleIds;//操作员角色
  const [dateList,setDateList] = useState([]);
  const [adjustForm] = Form.useForm();
  const [whetherReadonly, setWhetherReadonly] = useState<boolean>(false);
  const [editState, setEditState] = useState<boolean>(false);
  const [haveData, setHaveData] = useState<boolean>(true);
  const [saveButtonState, setSaveButtonState] = useState<boolean>(true);
  const [isRadio, setIsRadio] = useState<boolean>(true);
  const [spin, setSpin] = useState<boolean>(true);
  //附件bid  
  const [bid, setBid] = useState<string>('');
  
  var roleId = getSessionRoleData().roleCode;
  //采购方式
  const proMethod = getProMethod();
  let showNameT: any = { tbr: '', pb: '', tb: '' }//投标人供应商
  if (proMethod === 'procurement_mode_1' || proMethod === 'procurement_mode_2') {//招标
      showNameT = { tbr: '投标人', pb: '评标', tb: '投标' };
  } else {
      showNameT = { tbr: '供应商', pb: '评审', tb: '应答'  }
  }
  const columns: any[] = [  // 列表数据
    { title: `${showNameT.tbr}名称`, dataIndex: 'tendererName', key: 'tendererName' },
    { title: '最新不含税总价', dataIndex: 'evaluatingContent', key: 'evaluatingContent' },
    { title: '调整类别', dataIndex: 'type', key: 'type' ,render: (text: any, record: any, index: any) => {
      let a = "";
      if(record.tfileTendererprice!==null){
        a = typeValue(record.tfileTendererprice.type);
      }
      return a;
      }
    },
    { title: '调价说明', dataIndex: 'memo', key: 'memo',render: (text: any, record: any, index: any) =>  {
      var memo = "";
      if(record.tfileTendererprice!==null){
        memo = record.tfileTendererprice.memo;
      }
      return memo;
     }  
    },
    { title: '调价附件', dataIndex: 'fileId', key: 'fileId' ,render: (text: any, record: any, index: any) =>  {
      var dev = "";
      if(record.tfileTendererprice!==null){
        dev = <ExtendUpload bid={record.tfileTendererprice.fileId} uploadProps={{name:"file",disabled:true,uploadProps:true}}></ExtendUpload>
      }
      return dev;
     }  
    },
  ];
  useEffect(() => {
    getWarningList();
    setSpin(false);
    if(roleId!=="ebtp-expert"){
      setEditState(false);
      setHaveData(false);
    }
  },[]);

  const getWarningList = async() => {
      setSaveButtonState(false);
      let radioBoolean = false;
      await findArithmeticError(roomId).then((res) => {
        if (res.success ==true) {
          if(res.data!==1){
            radioBoolean = false;
            setIsRadio(false)
          }else{
            radioBoolean  = true;
          }
        }
      })

      await getList(roomId).then((res) => {
        if (res.success ==true) {
          var list = res.data;
          for(var i = 0 ; i < list.length ; i++){
            list[i]["key"] = i;
          }
          setDateList(list);
          setSelectChange(list);
          if(list===null||list.length===0){//
            setEditState(false);
            setHaveData(false);
            setIsRadio(false)
          }else{
            if(radioBoolean){
              setEditState(true);
              setIsRadio(true)
            }else{
              setEditState(false);
              setIsRadio(false)
            }
            
          }
        }
      })

  }

  const setSelectChange = async (list: any) => {
    const fieldsValue = await adjustForm.validateFields();
    if(fieldsValue!==null){
      
      for(var i = 0 ; i < list.length ; i ++){
        var data = list[i]; 
        
        if(data.id===fieldsValue.contentDataId){
          adjustForm.setFieldsValue({
            id:data.tfileTendererprice!==null
            &&data.tfileTendererprice!==undefined?data.tfileTendererprice.id:null,
            contentDataId:data.id,
            way: data.tfileTendererprice!==null
            &&data.tfileTendererprice!==undefined?parseInt(data.tfileTendererprice.way):1,
            type: data.tfileTendererprice!==null
            &&data.tfileTendererprice!==undefined?parseInt(data.tfileTendererprice.type):0,
            price: data.evaluating,
            newPrice: '',
            memo:data.tfileTendererprice!==null
            &&data.tfileTendererprice!==undefined?data.tfileTendererprice.memo:null,
            fileId:data.tfileTendererprice!==null
            &&data.tfileTendererprice!==undefined?data.tfileTendererprice.fileId:null
          });
        }
      }
    }
  }

  const onSelectChange = (nextTargetKeys: any, direction: any, moveKeys: any) => { // 单选中回执列表数据
    setEditState(true);
    var data = direction[0];
    //data.tfileTendererprice.id;
      adjustForm.setFieldsValue({
        id:data.tfileTendererprice!==null
        &&data.tfileTendererprice!==undefined?data.tfileTendererprice.id:null,
        contentDataId:data.id,
        way: data.tfileTendererprice!==null
        &&data.tfileTendererprice!==undefined?parseInt(data.tfileTendererprice.way):1,
        type: data.tfileTendererprice!==null
        &&data.tfileTendererprice!==undefined?parseInt(data.tfileTendererprice.type):0,
        price: data.evaluating,
        newPrice: '',
        memo:data.tfileTendererprice!==null
        &&data.tfileTendererprice!==undefined?data.tfileTendererprice.memo:null,
        fileId:data.tfileTendererprice!==null
        &&data.tfileTendererprice!==undefined?data.tfileTendererprice.fileId:null
      });

      setBid(data.tfileTendererprice!==null
        &&data.tfileTendererprice!==undefined
        &&data.tfileTendererprice.fileId!==null
        ?data.tfileTendererprice.fileId:"-1");
      
  }

  const formOnFinish = (data: any) => {
  }

  const normFile = (e: any) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  }
  const saveUpdate = async () => {
    const fieldsValue = await adjustForm.validateFields();
    if(fieldsValue.contentDataId===null||fieldsValue.contentDataId===""||fieldsValue.contentDataId===undefined){
      message.error(`请选择需要调整的供应商`);
      return;
    }
    var params = {
       "id":fieldsValue.id,
       "contentDataId":fieldsValue.contentDataId,
       "newPrice":fieldsValue.newPrice,
       "way":fieldsValue.way,
       "type":fieldsValue.type,
       "memo":fieldsValue.memo,
       "fileId":fieldsValue.fileId
    }
    setSaveButtonState(true);
    //保存
    savePrice(params).then((res) => {
      if (res.success ==true) {
        message.success(`保存成功`);
        getWarningList();//刷新
      }
    })
  }

  return (
    <>
    <div className="bidContent">
      <Spin spinning={spin}>
        <div className="titName">
          <span className="f16">{showNameT.tbr}最新报价列表</span>
          {!haveData?<span className="f16">（无报价数据）</span>:null}
          <Space className="fr">
          </Space>
        </div>
        
        {isRadio?
        <Table
          rowSelection={{
            type: 'radio',
            onChange: onSelectChange,
          }}
          bordered
          pagination={false}
          columns={columns}
          dataSource={dateList}
        />:<Table
          bordered
          pagination={false}
          columns={columns}
          dataSource={dateList}
        />}
        
        {editState?
        <div className="titName mt20">
          <span className="f16">算数错误调整</span>
        </div>:null
        }
        {editState?
        <Form
          name="validate_other"
          form={adjustForm}
          {...formItemLayout}
          onFinish={formOnFinish}
        >
          <Form.Item name="contentDataId" hidden={true}>
            <Input hidden />
          </Form.Item>
          <Form.Item name="id" hidden={true}>
            <Input hidden />
          </Form.Item>
          <Form.Item name="way" label="调价方式："  rules={[{ required: true, message: '请选择调价方式!' }]}>
            <Radio.Group>
              <Radio value={1}>最终价格</Radio>
              <Radio value={0}>调整价</Radio>
            </Radio.Group>
            
          </Form.Item>
          <Form.Item  rules={[{ required: true, message: '请选择调整类别!' }]}
            name="type"
            label="调整类别："
            hasFeedback
          >
            <Select style={{ width: 120 }}>
                <Option value={0}>小微</Option>
                <Option value={1}>缺项</Option>
                <Option value={2}>单价和总价不一致</Option>
                <Option value={3}>手动输入</Option>
            </Select >
          </Form.Item>
          <Form.Item name="price" label="原价：">
            <Input disabled />
          </Form.Item>
          <Form.Item name="newPrice" label="调整价：" rules={[{ required: true, message: '请输入调整价!' }]}>
            <Input placeholder="人民币" />
          </Form.Item>
          <Form.Item name="memo" label="调价说明：" rules={[{ required: true, message: '请输入调价说明!' }]}>
            <TextArea rows={4} />
          </Form.Item>
          <Form.Item
            label="附件"
            name="fileId">
            <ExtendUpload bid={bid} btnName="上传附件" uploadProps={{name:"file",disabled: whetherReadonly}}>
            </ExtendUpload>
          </Form.Item>
          <Form.Item>
          <div style={{textAlign: "center"}}>
          <Button type="primary" disabled={saveButtonState} onClick={async () => {
            
                saveUpdate();
              }}>保存</Button>
          </div>    
          </Form.Item>
        </Form>
        :null}
        </Spin>
      </div>
    </>
  )
}

export default Index