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, Table } from "antd"
import { Link } from "@ttk/router"
import { toFixed } from "@/utils/number"
import { transformSlv } from "@/utils"
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 goodsSearchForm = useData([props, 'goodsSearchForm']).toJS()
  const goodsTableData = useData([props, 'goodsTableData']).toJS()
  const { showGoodsModal: showModal, editId, editIndex,  defaultRate, rateList } = useData([props, 'tempState']).toJS()
  const { pageIndex, pageSize, recordCount } = useData([props, 'goodsPagination']).toJS()
  let { fymxList, hsbz, hsslbs } = useData([props, 'formObj']).toJS()
  
  // 内部管理loading状态
  const [loading, setLoading] = useState(false)

  async function fetchData(keyword) {
    setLoading(true)
    await actions.goodsTableData({hsslbs, keyword})
    setLoading(false)
  }

  // 初始化
  useEffect(() => {
    fetchData()
  }, []) 

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

  const onChose = useCallback((row) => {
    if (hsslbs == 2) {
      // 差额征税，须填写含税销售额和扣除额
      commit([props, "formObj"], { type: "update", data: {kce: "", tmpSalePrice: ""}})
      commit([props, "formObj"], { type: "update", data: {kce: "", tmpSalePrice: ""}})
      commit([props, "tempState"], { type: "setEditInfo", data: row})
      commit([props, "tempState"], { type: "setBalanceModal", data: true})
      commit([props, "tempState"], { type: "setGoodsModal", data: false})
      commit([props, "goodsTableData"], { type: "update", data: []})
      
      return
    }
    // 商品单价都是含税的
    // 商品税率列表处理，税率列表由后台通过税率规则给出
    let tmpRateList = [ ...rateList ]
    let sl = row.zzssl || defaultRate // 税率默认为税率列表的第一项
    
    if (row.taxPerferentialRateList) {
      // 如果是税收优惠政策的商品，则税率下拉使用商品信息带过来的税率列表taxPerferentialRate字段
      // 若商品的税率不在默认的税率范围内，则默认填入第一个税率（除0%外的税率），税率下拉依然为默认税率
      tmpRateList = row.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 == row.zzssl
    })
    if (!hasGoodsRate) {
      // 商品税率不包含在内，则选择下拉列表的第一项不为0的税率
      if (hsslbs == 0) {
        // 普通征税
        let notZero = tmpRateList.find((item) =>{
          return item.taxRate > 0
        })
        if (notZero) {
          sl = notZero.taxRate
        } else {
          tmpRateList.push({ taxRate: row.zzssl, taxRateLabel: toFixed(row.zzssl * 100, 1) + "%" }) // 将商品税率添加至税率列表
          // 税率列表排序
          tmpRateList.sort((a, b) =>{
            return a.taxRate - b.taxRate
          })
        }
      } else if (hsslbs == 1) {
        // 减按征税， 只能选择0.015
        sl = "0.015"
      }
    }

    sl = Number(sl)
    let dj, tmpDj, tmpHsdj
    
    tmpHsdj = row.xmdj
    tmpDj = row.xmdj && sl > -1 && row.xmdj / ( 1 + sl)
    if (hsbz) {
      // 含税单价
      dj = tmpHsdj
    } else {
      // 不含税单价
      dj = tmpDj
    }
    
    row = {
      ...row, 
      spId: row.id, // 商品id
      hsbz: hsbz ? 1 : 0, 
      spmc: (row.spbmjc ? "*" + row.spbmjc + "*" : "") + row.spmc, 
      spbm: row.ssflbm, // 税收分类编码
      dj: toFixed(dj, djFloat), 
      tmpDj: toFixed(tmpDj, djFloat), 
      tmpHsdj: toFixed(tmpHsdj, djFloat), // 含税单价
      se: "",
      je: "",
      fphxz: 0, // 发票行性质, 0 正常行、1 折扣行、2 被折扣行
      zkType: "1", // 折扣方式, 1按比例，2按金额
      sl: sl + '',
      zxbm: row.bm, // 商品自行编码，沿用商品编码
      yhzcbs: row.yhzcbs, // 税收优惠标识
      lslbs: row.lslbs ,
      zzstsgl: row.yhzclx,
      tmpRateList,
    }
    if (editIndex != null) {
      fymxList.splice(editIndex, 1, row)
    } else {
      fymxList.push(row)
    }
    // commit([props, 'formObj'], { type: "update", data: { fymxList }})
    actions.updateKjmxlist(fymxList)
    commit([props, 'tempState'], { type: "setGoodsModal", data: false })
    commit([props, "goodsTableData"], { type: "update", data: []})
    commit([props, 'tempState'], { type: "setEditIndex", data: null })
    commit([props, 'goodsSearchForm'], { type: "init" })
  }, [hsslbs, fymxList, defaultRate, editIndex, hsbz])

  const onPageSizeChange = useCallback((current, pageSize) => {
    return async function () {
      await actions.updateGoodsSearchForm({ pageSize })
      fetchData(goodsSearchForm.spmc)
    }()
  }, [goodsSearchForm])

  const onPageChange = useCallback((page, pageSize) => {
    return async function () {
      await actions.updateGoodsSearchForm({ pageIndex: page })
      fetchData(goodsSearchForm.spmc)
    }()
  }, [goodsSearchForm])

  const onSearch = useCallback(() => {
    return async function () {
      await actions.updateGoodsSearchForm({ pageIndex: 1 })
      fetchData(goodsSearchForm.spmc)
    }()
  }, [goodsSearchForm])

  // 清除方法
  const onCancel = useCallback(() => {
    commit([props, 'tempState'], { type: 'setGoodsModal', data: false })
    commit([props, "goodsTableData"], { type: "update", data: []})
    commit([props, 'tempState'], { type: "setEditId", data: "" })
    commit([props, 'tempState'], { type: "setEditIndex", data: null })
    commit([props, 'goodsSearchForm'], { type: "init" })
  }, [])

  const tableThead = [{
    dataIndex: 'bm',
    key: 'bm',
    title: '商品编号',
    width: 120,
    ellipsis: true,
    align: "center",
  }, {
    dataIndex: 'spmc',
    key: 'spmc',
    title: '商品名称',
    ellipsis: true,
    align: "center",
  }, {
    dataIndex: 'ssflbm',
    key: 'ssflbm',
    title: '税收分类编码',
    width: 100,
    ellipsis: true,
    align: "center",
  }, {
    dataIndex: 'zzssl',
    key: 'zzssl',
    title: '税率',
    width: 60,
    ellipsis: true,
    align: "center",
    render: (text, row, rowIndex) => {
      const {zzssl,yhzclx} = row;
      return transformSlv({zzssl, yhzclx})
    }
  }, {
    dataIndex: 'yhzclx',
    key: 'yhzclx',
    title: '税收优惠政策',
    width: 120,
    ellipsis: true,
    align: "center",
    render: (text) => {
      return text || '-'
    }
  }, {
    dataIndex: 'lslbsDesc',
    key: 'lslbsDesc',
    title: '免税类型',
    width: 100,
    ellipsis: true,
    align: "center",
    render: (text) => {
      return text || '-'
    }
  }, {
    dataIndex: 'ggxh',
    key: 'ggxh',
    title: '规格型号',
    width: 80,
    ellipsis: true,
    align: "center",
    render: (text) => {
      return text || '-'
    }
  }, {
    dataIndex: 'xmdj',
    key: 'xmdj',
    title: '单价',
    width: 100,
    ellipsis: true,
    align: "center",
    render: (text) => {
      return text || '-'
    }
  }, {
    dataIndex: 'operation',
    key: 'operation',
    className: "operationcell",
    title: '操作',
    width: 80,
    render: (text, row, rowIndex) => {
      return (
        <span onClick={() => onChose(row)}>选择</span>
      )
    }
  }]

  return (
    <Modal
      className="ttk-card-form"
      width={1000}
      height={600}
      title="选择商品信息"
      visible={showModal}
      footer={false}
      maskClosable={false}
      onCancel={onCancel}
    >
        <Spin>
            <Card bordered={true} style={{marginBottom:10}}>
              <Row>
                <Form layout="inline">
                  <Form.Item>
                    <Input className="mk-input" allowClear value={goodsSearchForm.spmc} placeholder="请输入商品编码/商品名称进行查询" onChange={e => updateForm({ spmc: e.target.value })} style={{ width: 300 }}/>
                    <Button type="primary" onClick={onSearch} style={{ marginLeft: "10px" }}>查询</Button>
                  </Form.Item>
                </Form>
              </Row>
              <Row>
                <Table loading={loading} bordered className="mk-table" dataSource={goodsTableData} columns={tableThead} pagination={false} rowKey="id"/>
               
              </Row>
            </Card>
            <Row style={{ margin: "10px 0", padding: "0 10px" }}>
              <Pagination
                pageSize={pageSize}
                total={recordCount}
                current={pageIndex}
                showSizeChanger={true}
                pageSizeOptions={['10', '20', '50', '100', '200', '300', '400']}
                onChange={onPageChange}
                onShowSizeChange={onPageSizeChange}
              />
            </Row>
        </Spin>
        <span>没有找到所需的商品信息? </span><Link to="/app-root/layout/goods-maintain">去新增</Link>
    </Modal>
  )
}