import webapi from '../webapi'
import { commit } from '@ttk/app-loader'
import schema from 'async-validator'
import { slFloat, jeFloat, djFloat } from "@/apps/app-demo/invoice-manage/constant"
import { toFixed, toRMB, toFixedForce, minusSign } from "@/utils/number"
import uuid, { code32 } from '@/utils/uuid'
import * as validator from '@/utils/validator'
import { calcPutongPrice, calcJiananPrice, calcChaePrice } from "../../invoice-calc"
import { rules, balanceRules, goodsRules } from "./rules"
import { isNotEmpty, transformSlv } from "@/utils"

export * from './goodsModal.js'
export * from './customModal.js'

// 更新fymxList
export function updateKjmxlist(reduce, gf, fymxList) {
  return async (dispatch, getState) => {
    let data = {
      fymxList
    }
    if (!fymxList || !fymxList.length) {
      let { rateList } = gf(["tempState"])
      fymxList = [{
        spmc: "", // 商品为空时，经校验后，显示 请选择商品 的提示
        fphxz: 0,
        tmpIsDefault: true,
        tmpRateList: rateList
      }]
      data = {
        fymxList
      }
    } else {
      fymxList = fymxList.filter((item) => {
        return !item.tmpIsDefault
      })
      data = {
        fymxList
      }
    }
    // 将首列  请选择商品  的提示状态清除
    reduce('validateState', { type: 'update_goods', data: {spmc: { state: 'success', message: '' }}, index: 0 })
    // 更新表单数据
    reduce('formObj', { type: 'update', data })
    dispatch(sumAmount(reduce, gf)) // 算总额
  }
}

// 重置表单（可用于开票成功后清空表单）
export function resetForm(reduce, gf) {
  return async (dispatch, getState) => {
    // 重置表单数据
    reduce('formObj', { type: 'reset' })
    dispatch(updateKjmxlist(reduce, gf))
  }
}

// 更新表单
export function updateForm(reduce, gf, fields) {
  return async (dispatch, getState) => {
    if (!fields)
      fields = gf(['formObj'])
    // Object.keys(fields).forEach((key) => {
    //   if (typeof fields[key] == "string") {
    //     fields[key] = fields[key].replace(/^\s|\s$/g, "")
    //   }
    // })
    let rowFields = gf(['formObj'])
    // 字段校验。返回一个长度为2的数组，第一个是boolean值，代表是否校验成功，第二个是错误消息状态
    const [result, resultObj] = await validator.fieldValidator(fields, rules, rowFields)
    // 更新文本域验证状态
    reduce('validateState', { type: 'update', data: resultObj })
    // 更新表单数据
    reduce('formObj', { type: 'update', data: fields })
    return result
  }
}

// 更新表单
export function updateBalanceForm(reduce, gf, fields) {
  return async (dispatch, getState) => {
    if (!fields)
      fields = gf(['formObj'])
    // 字段校验。返回一个长度为2的数组，第一个是boolean值，代表是否校验成功，第二个是错误消息状态
    const [result, resultObj] = await validator.fieldValidator(fields, balanceRules)
    // 更新文本域验证状态
    reduce('validateState', { type: 'update', data: resultObj })
    // 更新表单数据
    reduce('formObj', { type: 'update', data: fields })
    return result
  }
}

// 更新表单
export function updateGoodsForm(reduce, gf, fields, index) {
  return async (dispatch, getState) => {
    if (!fields) {
      fields = gf(["formObj", "fymxList", index])
    }
    if (isNotEmpty(fields.sl)) {
      fields.sl += ''
    }
    let rowFields = gf(["formObj", "fymxList", index])
    // 字段校验。返回一个长度为2的数组，第一个是boolean值，代表是否校验成功，第二个是错误消息状态
    const [result, resultObj] = await validator.fieldValidator(fields, goodsRules, rowFields)
    // 更新文本域验证状态
    reduce('validateState', { type: 'update_goods', data:resultObj, index })
    // 更新表单数据
    reduce('formObj', { type: 'update_goods', data: fields, index })
    dispatch(sumAmount(reduce, gf)) // 算总额
    return result
  }
}

export function sumAmount(reduce, gf) {
  return async (dispatch, getState) => {
  let formObj = gf(["formObj"]) // 获取最新数据
    
    // 计算总额
    let { fymxList } = formObj // je合计金额 se合计税额 jshj价税合计
    let hjje = 0
    let hjse = 0
    let jshj = 0
    let tmpJshj = ""
    if (fymxList && fymxList.length) {
      fymxList.forEach((item) => {
        hjje += Number(item.tmpJe) || 0
        hjse += Number(item.se) || 0
      })
      jshj = hjje + hjse
      
      hjje = toFixedForce(hjje, jeFloat)
      hjse = toFixedForce(hjse, jeFloat)
      jshj = toFixedForce(jshj, jeFloat)
      tmpJshj = toRMB(jshj)
      reduce("formObj", { type: "update", data: { hjje, hjse, jshj, tmpJshj } })
    }
  }
}

// 提交表单
export function submitForm(reduce, gf) {
  return async (dispatch, getState) => {
    let fields = gf(['formObj'])
    let result = await dispatch(updateForm(reduce, gf, fields))
    if (fields.fymxList.length) {
      for (let i in fields.fymxList) {
        let tmp = fields.fymxList[i]
        
        // 用for in保证同步
        if (tmp && tmp.fphxz != 0) {
          continue
        }
        let tmpRes = await dispatch(updateGoodsForm(reduce, gf, fields.fymxList[i], i))
        result = result && tmpRes
      }
    }
    
    if (!result) {
      return false
    }

    fields.fymxList = fields.fymxList.map((item) => {
      if (fields.hsslbs != 1) {
        item.hsbz = 0 // 含税标志为0
        item.je = item.tmpJe // 提交数据的金额是不含税金额
        item.dj = item.spsl && (item.tmpDj || "") // 提交数据的金额是不含税金额，另外，数量跟单价需同时为空或不为空
      } else {
        // 减按征收的不含税金额都按含税金额算，提交时也是提交含税金额
        item.hsbz = 1 // 含税标志为1
        item.hsje = item.je // 含税金额
        item.hsdj = item.spsl && item.dj // 含税单价
        item.je = item.tmpJe // 提交数据的金额是不含税金额
        item.dj = item.spsl && (item.tmpDj || "") // 提交数据的金额是不含税金额，另外，数量跟单价需同时为空或不为空
      }
      if (item.sl && item.sl.includes("%")) {
        // 将百分号税率转成小数
        item.sl = item.sl.replace("%", "") / 100
      }
      delete item.tmpRateList
      delete item.taxPerferentialRateList
      return item
    })
    // 特殊处理，税局要求扣除额必须保留2位小数，整数也需要
    if (fields.kce) {
      fields.kce = toFixedForce(fields.kce, jeFloat)
    }
    let fpqqlsh = code32()
    fields = { ...fields, fpqqlsh }
    
    // 提交表单
    let res = await webapi.create(fields)
    if (res === undefined) {
      return false
    } else {
      return true
    }
  }
}

// 税率列表
export function rateListData(reduce, gf, param) {
  return async (dispatch, getState) => {
    let res = await webapi.rateListData(param)
    if (res) {
      let data = res.taxRateList
      data.sort((a, b) => {
        return a.taxRate - b.taxRate
      })
      data = data.map((item) => {
        item = {
          ...item,
          taxRateLabel: (item.taxRate * 100) + "%"
        }
        return item
      })
      reduce('tempState', { type: 'setRateList', data })
      if (data && data.length) {
        // 默认税率为第一个不为0的税率
        if (data[0].taxRate > 0) {
          reduce('tempState', { type: 'setDefaultRate', data: data[0].taxRate })
        } else if (data[1]) {
          reduce('tempState', { type: 'setDefaultRate', data: data[1].taxRate })
        }
      }
      return data
    }
    return false
  }
}

// 销售方初始数据
export function myInitData(reduce, gf, param) {
  return async (dispatch, getState) => {
    param.interceptConfigAll = true // 自己处理返回
    let res = await webapi.myInitData(param)
    const { head, body } = res

    if (head.errorCode == "0") {
      let data = body
      let { skr, kpr, fhr, xhdwmc, xhdwdzdh, xhdwsbh, xhdwyhzh } = data
      if (data.xhdwyhzhList && data.xhdwyhzhList.length) {
        xhdwyhzh = data.xhdwyhzhList[0]
      }
      reduce('formObj', { type: 'update', data: { skr, kpr, fhr, xhdwmc, xhdwdzdh, xhdwsbh, xhdwyhzh } })
      reduce('tempState', { type: 'setMyInitData', data })

      return data
    } else if (head.errorCode == "300201") {
      reduce('tempState', { type: 'setLimitModal', data: true })
    } else if (head.errorCode == "300202") {
      reduce('tempState', { type: 'setOutdateModal', data: true })
    }
    return false
  }
}

// 获取发票红冲信息
export function hcDetail(reduce, gf, param) {
  return async (dispatch, getState) => {
    let res = await webapi.hcDetail(param)
    if (res) {
      console.log('res', res)
      let data = res
      data.fymxList = data.fymxList.filter((item, index) => {
        // 发票红冲不显示折扣行，但折扣行的数据要叠加到被折扣行
        let nextRow = data.fymxList[index + 1]
        item.spsl= item.spsl? `-${item.spsl}` : ''
        if (item.fphxz == 2 && nextRow) {
          // 金额=-1*（被折扣行金额+折扣行金额）
          item.je = `-${toFixed(item.je + Number(nextRow.je), 2)}`
          // 被折扣行的税额+折扣行税额
          item.se = minusSign(toFixed(item.se + Number(nextRow.se), 2))
          item.dj = item.je && item.spsl && toFixed((item.je / item.spsl), djFloat)
          item.fphxz = 0
        } else {
          // 正常行金额直接赋值
          item.je = `-${item.je}`
          item.se = minusSign(item.se)
          item.dj = toFixed(item.dj, djFloat)
        }
        const {sl, zzstsgl} = item;
        item.sl = transformSlv({zzssl: sl, yhzclx: zzstsgl})
        return item.fphxz != 1 
      })
      data.tmpBz = data.bz
      data.bz = `对应正数发票代码:${data.fpdm} 号码:${data.fphm}` + (data.hsslbs == 2 ? " 差额征税" : "") + (` ${data.bz ? data.bz : ""}`)
      // delete data.fpHwxxList
      data = {
        ...data,
        hsbz: (data.fymxList?.[0]?.hsbz == 1) ? true : false,
        kplx: 1,
        jshj: `-${data.jshj}`,
        hjse: minusSign(data.hjse),
        hjje: `-${data.hjje}`,
        tmpJshj: `负${toRMB(data.jshj)}`,
        yfpdm: data.fpdm,
        yfphm: data.fphm,
        ykprq: data.kprq,
        yfplx: data.fplxdm,
      }
      delete data.kce
      reduce('formObj', { type: 'update', data: data })
      return data
    }
    return false
  }
}

// 提交红冲表单
export function submitFormHc(reduce, gf) {
  return async (dispatch, getState) => {
    let fields = gf(['formObj'])
    let fpqqlsh = code32()
    fields = { ...fields, fpqqlsh }
    fields.fymxList = fields.fymxList.map((item) => {
      if (fields.hsslbs != 1) {
        item.hsbz = 0 // 含税标志为0
      } else {
        // 减按征收的不含税金额都按含税金额算，提交时也是提交含税金额
        item.hsbz = 1 // 含税标志为1
        item.hsje = item.je // 含税金额
        item.hsdj = item.spsl && item.dj // 含税单价
      }
      // if (item.sl && item.sl.includes("%")) {
      if (item.sl && /%/.test(item.sl)) {
        // 将百分号税率转成小数
        item.sl = item.sl.replace("%", "") / 100
      } else if (item.sl && /[^\x00-\xff]/g.test(item.sl)) {
        item.sl = "0"
      }
      delete item.tmpRateList
      delete item.taxPerferentialRateList
      return item
    })
    fields.bz = fields.tmpBz
    // 提交表单
    let res = await webapi.create(fields)
    if (res === undefined) {
      return false
    } else {
      return true
    }
  }
}

// 获取重开发票信息
export function ckDetail(reduce, gf, param) {
  return async (dispatch, getState) => {
    let res = await webapi.ckDetail(param)
    let { rateList } = gf(["tempState"])
    if (res) {
      let data = res
      data.fymxList = data.fpHwxxList.map((item, index) => {
        let result = {}
        // 换算出不含税金额、不含税单价、含税金额、含税单价
        if (data.hsslbs == 0) {
          result = calcPutongPrice( {...item, value: item.je, index })
        } else if (data.hsslbs == 1) {
          result = calcJiananPrice( {...item, value: item.je, index })
        } else if (data.hsslbs == 2) {
          result = calcChaePrice( {...item, value: item.je, index })
        }
        item.tmpJe = result.tmpJe
        item.tmpDj = result.tmpDj
        item.tmpHsje = result.tmpHsje
        item.tmpHsdj = result.tmpHsdj
        return item
      })
      delete data.fpHwxxList
      data = {
        ...data,
        hsbz: (data.fymxList?.[0]?.hsbz == 1) ? true : false,
        tmpJshj: `${toRMB(data.jshj)}`,
      }
      reduce('formObj', { type: 'update', data: data })
      return data
    }
    return false
  }
}

// 实时查询客户列表
export function searchCustomerList(reduce, gf, fields) {
  return async (dispatch, getState) => {
    let data = []
    fields = { ...fields, pageIndex:1, pageSize: 10 }
    let res = await webapi.customTableData(fields)
    if (res) {
      data = res.data
      data = data.map((item) => {
        item = { ...item, value: item.id, text: item.qyMc }
        return item
      })
      reduce('tempState', { type: 'setSearchCustomerList', data: data })
    }
  }
}