import React, { useState, useCallback, useEffect } from 'react'
import { Spin, Card, Layout, Row, Col, Form, Input, Checkbox, AntdSelect as Select, Button, DataGrid, Pagination } from '@ttk/component'
import { Modal } from "antd"
import { Link } from "@ttk/router"
import { toFixed, toFixedForce } from "@/utils/number"
import { slFloat, jeFloat, djFloat } from "@/apps/app-demo/invoice-manage/constant"
import { useData, useActions, useCommit } from '@ttk/app-loader'

export default function Component(props) {

  const commit = useCommit()
  const actions = useActions(props)
  const validateState = useData([props, 'validateState']).toJS()
  const { showBalanceModal: showModal, editId, editIndex,  defaultRate, rateList, editInfo } = useData([props, 'tempState']).toJS()
  let { fymxList, hsbz, hsslbs, kce, tmpSalePrice } = useData([props, 'formObj']).toJS()
  const [ loading, setLoading ] = useState(false)

  // 更新表单方法
  const updateForm = useCallback((e) => {
    async function asyncFun(arges) {
      await actions.updateBalanceForm(e)
    }
    asyncFun(e)
  }, [])

  /**
   * 差额征税 金额计算
   * 
   * 先算税额，若（含税销售额-扣除额）>0,税额=（含税销售额-扣除额）*（税率或征收率）/（1+税率或征收率），若（含税销售额-扣除额）<=0，则税额=0，再算金额=含税销售额-税额，如果数量不为空，则不含税单价=金额/数量,若数量为空，则不含税单价也为空。
   *  */
  const onOk = useCallback(() => {
    async function asyncFunc() {
      setLoading(true)
      let result = await actions.updateBalanceForm()
      if (!result) {
        return
      }
      tmpSalePrice = Number(tmpSalePrice)
      kce = Number(kce)
      if (editId) {
        edit(rateList, editInfo, tmpSalePrice, kce)
      } else {
        add(rateList, editInfo, tmpSalePrice, kce)
      }
      actions.updateForm({kce: toFixed(kce, 2)})
      setLoading(false)
    }
    asyncFunc()
  }, [editId, rateList, editInfo, defaultRate, tmpSalePrice, kce])

  async function add (rateList, editInfo, tmpSalePrice, kce) {
    // 商品税率列表处理，税率列表由后台通过税率规则给出
    let tmpRateList = [ ...rateList ]
    let se = "" // 税额
    let je = ""
    let sl = editInfo.zzssl || defaultRate // 税率默认为税率列表的第一项
    tmpRateList = tmpRateList.filter((item) => {
      return item.taxRate != 0.015
    })
    if (editInfo.taxPerferentialRateList) {
      // 如果是税收优惠政策的商品，则税率下拉使用商品信息带过来的税率列表taxPerferentialRate字段
      // 若商品的税率不在默认的税率范围内，则默认填入第一个税率（除0%外的税率），税率下拉依然为默认税率
      tmpRateList = editInfo.taxPerferentialRateList.map((rate) => {
        let item = {
          taxRate: rate.value,
          taxRateLabel: rate.desc
        }
        return item
      })
    }
    
    // 税率列表排序
    tmpRateList.sort((a, b) =>{
      return a.taxRate - b.taxRate
    })
    
    let hasGoodsRate = tmpRateList.find((item) =>{
      return item.taxRate == editInfo.zzssl
    })
    if (!hasGoodsRate) {
      // 商品税率不包含在内，则选择下拉列表的第一项不为0的税率
      // 差额征税，不能选择0.015
      if (editInfo.zzssl != 0.015) {
        let notZero = tmpRateList.find((item) =>{
          return item.taxRate > 0
        })
        if (notZero) {
          sl = notZero.taxRate
        } else {
          tmpRateList.push({ taxRate: editInfo.zzssl, taxRateLabel: toFixed(editInfo.zzssl * 100, 1) + "%" }) // 将商品税率添加至税率列表
          // 税率列表排序
          tmpRateList.sort((a, b) =>{
            return a.taxRate - b.taxRate
          })
        }
      } else {
        sl = defaultRate // 若商品税率为0.015时，切换到默认税率
      }
    }
    
    sl = Number(sl)
    if (tmpSalePrice > kce) {
      se = (tmpSalePrice - kce) * sl / (1 + sl)
    } else {
      se = 0
    }

    je = tmpSalePrice - se

    // 不含税单价 数量
    let dj, tmpDj, spsl
    dj = tmpDj = editInfo.xmdj && sl && editInfo.xmdj / ( 1 + sl)
    if (editInfo.xmdj && sl) {
      dj = tmpDj = editInfo.xmdj / ( 1 + sl)
      spsl = je / dj
    }
    
    // 取小数位并四舍五入
    je = toFixedForce(je, jeFloat)
    se = toFixedForce(se, jeFloat)
    dj = toFixed(dj, djFloat)
    tmpDj = toFixed(tmpDj, djFloat)
    spsl = toFixed(spsl, djFloat)

    let row = {
      ...editInfo,
      spId: editInfo.id, // 商品id
      spbm: editInfo.ssflbm, // 商品编码
      zxbm: editInfo.bm, // 商品自行编码，沿用商品编码
      yhzcbs: editInfo.yhzcbs, // 税收优惠标识
      lslbs: editInfo.lslbs,
      zzstsgl: editInfo.yhzclx,
      hsbz: hsbz ? 1 : 0, 
      fphxz: 0,
      spmc: (editInfo.spbmjc ? "*" + editInfo.spbmjc + "*" :"") + editInfo.spmc, 
      je,
      tmpJe: je,
      se,
      sl: sl + '',
      dj,
      tmpDj,
      spsl,
      tmpRateList,
    }
    
    fymxList = [row]
    // commit([props, 'formObj'], { type: "update", data: { fymxList }})
    await actions.updateKjmxlist(fymxList)
    actions.updateGoodsForm(null, 0) // 这里一定要调用updateGoodsForm，以便更新合计
    onCancel()
  }

  async function edit (rateList, editInfo, tmpSalePrice, kce) {
    let { je, se, spsl, sl, dj } = editInfo
    sl = Number(sl)
    if (tmpSalePrice > kce) {
      se = (tmpSalePrice - kce) * sl / (1 + sl)
    } else {
      se = 0
    }

    je = tmpSalePrice - se
    if (spsl && spsl != 0) {
      dj = je / spsl
    } else if (dj && dj != 0) {
      spsl = je / dj
    }
    
    // 取小数位并四舍五入
    je = toFixedForce(je, jeFloat)
    se = toFixedForce(se, jeFloat)
    dj = dj && toFixed(dj, djFloat)
    spsl = spsl && toFixed(spsl, slFloat)
    let row = {
      ...editInfo, 
      je, 
      tmpJe: je,
      se,
      dj,
      spsl,
    }
    fymxList = [row]
    commit([props, 'formObj'], { type: "update", data: { fymxList }})
    actions.updateGoodsForm(null, 0) // 这里一定要调用updateGoodsForm，以便更新合计
    onCancel()
  }

  // 取消
  const onCancel = useCallback(() => {
    commit([props, 'tempState'], { type: 'setBalanceModal', data: false })
    commit([props, 'tempState'], { type: "setEditInfo", data: {} })
    commit([props, 'tempState'], { type: "setEditId", data: null })
    commit([props, 'tempState'], { type: "setEditIndex", data: null })
    commit([props, 'goodsSearchForm'], { type: "init" })
  }, [])

  return (
    <Modal
      className="balance-modal"
      width={380}
      height={400}
      title="差额设置"
      visible={showModal}
      maskClosable={false}
      okText="确定"
      cancelText="取消"
      confirmLoading={loading}
      onOk={onOk}
      onCancel={onCancel}
    >
      <Row>
        <Form>
          <Form.Item label="含税销售额"
            required={true}
            validateStatus={validateState.tmpSalePrice.state}
            help={validateState.tmpSalePrice.message}>
            <Input value={tmpSalePrice} placeholder="请输入含税销售额" onChange={e => updateForm({ tmpSalePrice: e.target.value })}/>
          </Form.Item>
          <Form.Item label="扣除额"
            required={true}
            validateStatus={validateState.kce.state}
            help={validateState.kce.message}>
            <Input value={kce} placeholder="请输入扣除额" onChange={e => updateForm({ kce: e.target.value })}/>
          </Form.Item>
        </Form>
      </Row>
    </Modal>
  )
}