package com.cwhelp.admin.business.controller;

import com.alibaba.fastjson.JSONObject;
import com.cwhelp.admin.business.validator.BssVatInvoiceCheckValid;
import com.cwhelp.admin.business.validator.BssVatInvoiceValid;
import com.cwhelp.common.api.baidu.BaiduAipOCR;
import com.cwhelp.common.api.baidu.entity.vatinvoice.*;
import com.cwhelp.common.api.baidu.entity.vatinvoice.enums.VatInvoiceTypeEnum;
import com.cwhelp.common.enums.InvoiceTypeEnum;
import com.cwhelp.common.enums.StatusEnum;
import com.cwhelp.common.utils.*;
import com.cwhelp.common.vo.ResultVo;
import com.cwhelp.component.fileUpload.FileUpload;
import com.cwhelp.component.shiro.ShiroUtil;
import com.cwhelp.devtools.generate.utils.jAngel.utils.StringUtil;
import com.cwhelp.modules.business.domain.BssGoods;
import com.cwhelp.modules.business.domain.BssTaxinfo;
import com.cwhelp.modules.business.domain.BssVatInvoice;
import com.cwhelp.modules.business.service.BssTaxinfoService;
import com.cwhelp.modules.business.service.BssVatInvoiceService;
import com.cwhelp.modules.system.domain.Upload;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yan.y
 * @date 2019/08/26
 */
@Controller
@RequestMapping("/bss/vatInvoice")
public class BssVatInvoiceController {

    @Autowired
    private BssVatInvoiceService bssVatInvoiceService;

    @Autowired
    private BssTaxinfoService bssTaxinfoService;

    /**
     * 列表页面
     */
    @GetMapping("/index")
    @RequiresPermissions("bss:vatInvoice:index")
    public String index(Model model, BssVatInvoice bssVatInvoice) {

        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching();

        // 获取数据列表
        Example<BssVatInvoice> example = Example.of(bssVatInvoice, matcher);
        Page<BssVatInvoice> list = bssVatInvoiceService.getPageList(example);

        // 封装数据
        model.addAttribute("list", list.getContent());
        model.addAttribute("page", list);
        return "/business/vatInvoice/index";
    }

    /**
     * 跳转到添加页面
     */
    @GetMapping("/add")
    @RequiresPermissions("bss:vatInvoice:add")
    public String toAdd() {
        return "/business/vatInvoice/add";
    }

    /**
     * 跳转到编辑页面
     */
    @GetMapping("/edit/{id}")
    @RequiresPermissions("bss:vatInvoice:edit")
    public String toEdit(@PathVariable("id") BssVatInvoice bssVatInvoice, Model model) {
        model.addAttribute("bssVatInvoice", bssVatInvoice);
        return "/business/vatInvoice/edit";
    }

    /**
     * 查验录入
     * @return
     */
    @PostMapping("/check")
    @RequiresPermissions("bss:vatInvoice:add")
    public String check(@Validated BssVatInvoiceCheckValid checkValid, BssVatInvoice bssVatInvoice){
        JSONObject params = new JSONObject();
        //发票代码
        params.put("fpdm", bssVatInvoice.getInvoiceCode());
        //发票号码
        params.put("fphm", bssVatInvoice.getInvoiceNo());
        //开票日期
        params.put("kprq", bssVatInvoice.getInvoiceDate());
        //开具金额(不含税)
        params.put("kjje", bssVatInvoice.getInvoiceMoney());
        //校验码
        params.put("jym", bssVatInvoice.getCheckCode());
        JSONObject vatInfoiceInfo = HttpYoushangFapiaoUtil.getVatInfoiceInfo(params);


        return null;
    }

    /**
     * 保存添加/修改的数据
     * @param
     */
    @PostMapping({"/add","/edit"})
    @RequiresPermissions({"bss:vatInvoice:add","bss:vatInvoice:edit"})
    @ResponseBody
    public ResultVo save(@Validated @RequestBody BssVatInvoiceValid valid, @RequestBody BssVatInvoice bssVatInvoice) {
//    public ResultVo save(@Validated @RequestBody BssVatInvoice bssVatInvoice) {
        // 复制保留无需修改的数据
        if (bssVatInvoice.getId() != null) {
            BssVatInvoice beBssVatInvoice = bssVatInvoiceService.getById(bssVatInvoice.getId());
            EntityBeanUtil.copyProperties(beBssVatInvoice, bssVatInvoice);
            bssVatInvoice.setSalerTaxInfo(beBssVatInvoice.getSalerTaxInfo());
            bssVatInvoice.setBuyTaxInfo(beBssVatInvoice.getBuyTaxInfo());
        }else {
            if(!StringUtil.isBlank(String.valueOf(bssVatInvoice.getSalerTaxInfoId()))){
                bssVatInvoice.setSalerTaxInfo(bssTaxinfoService.getById(bssVatInvoice.getSalerTaxInfoId()));
            }
            if(!StringUtil.isBlank(String.valueOf(bssVatInvoice.getBuyTaxInfoId()))) {
                bssVatInvoice.setBuyTaxInfo(bssTaxinfoService.getById(bssVatInvoice.getBuyTaxInfoId()));
            }
            List<BssGoods> bssGoods = bssVatInvoice.getBssGoods();
            if(bssGoods != null && bssGoods.size() > 0){
                bssGoods.stream().forEach(good ->{
                    good.setVatInvoice(bssVatInvoice);
                });
            }
        }
        // 保存数据
        bssVatInvoiceService.save(bssVatInvoice);
        return ResultVoUtil.SAVE_SUCCESS;
    }

    /**
     * 跳转到详细页面
     */
    @GetMapping("/detail/{id}")
    @RequiresPermissions("bss:vatInvoice:detail")
    public String toDetail(@PathVariable("id") BssVatInvoice bssVatInvoice, Model model) {
        model.addAttribute("bssVatInvoice",bssVatInvoice);
        return "/business/vatInvoice/detail";
    }

    /**
     * 设置一条或者多条数据的状态
     */
    @RequestMapping("/status/{param}")
    @RequiresPermissions("bss:vatInvoice:status")
    @ResponseBody
    public ResultVo status(
            @PathVariable("param") String param,
            @RequestParam(value = "ids", required = false) List<Long> ids) {
        // 更新状态
        StatusEnum statusEnum = StatusUtil.getStatusEnum(param);
        if (bssVatInvoiceService.updateStatus(statusEnum, ids)) {
            return ResultVoUtil.success(statusEnum.getMessage() + "成功");
        } else {
            return ResultVoUtil.error(statusEnum.getMessage() + "失败，请重新操作");
        }
    }


    /**
     * 上传发票图片
     */
    @PostMapping("/upload/image")
    @ResponseBody
    public ResultVo uploadImage(@RequestParam("image") MultipartFile multipartFile) {

        // 创建Upload实体对象
        Upload upload = FileUpload.getFile(multipartFile, "/images");
        try {
            FileUpload.transferTo(multipartFile, upload);
            File destFile = FileUpload.getDestFile(upload);
            VatInvoiceResult vatInvoiceResult = (VatInvoiceResult)BaiduAipOCR.queryBaiduVatInvoiceApi(destFile, InvoiceTypeEnum.ADD_VALUE_TAX_INVOICE.getCode());
            WordsResult wordsResult = vatInvoiceResult.getWords_result();
            BssVatInvoice vatInvoice = new BssVatInvoice();
            Long bssplatformId = ShiroUtil.getSubject().getBssPlatform().getId();
            //add by hjc 发票上扫到的买卖双方如果不在系统中先入库
            if(!StringUtil.isBlank(wordsResult.getSellerRegisterNum())){
                BssTaxinfo sellerTaxInfo = new BssTaxinfo();
                BssTaxinfo taxNo = bssTaxinfoService.getByTaxNo(wordsResult.getSellerRegisterNum());
                if(taxNo == null){
                    //销售方
                    sellerTaxInfo.setName(wordsResult.getSellerName());
                    sellerTaxInfo.setTaxNo(wordsResult.getSellerRegisterNum());
                    sellerTaxInfo.setAccount(wordsResult.getSellerBank());
                    sellerTaxInfo.setAddressPhone(wordsResult.getSellerAddress());
                    sellerTaxInfo.setPlatformId(bssplatformId);
                    bssTaxinfoService.save(sellerTaxInfo);
                    vatInvoice.setSalerTaxInfoId(sellerTaxInfo.getId());
                }else {
                    vatInvoice.setSalerTaxInfoId(taxNo.getId());
                }
            }

            if(!StringUtil.isBlank(wordsResult.getPurchaserRegisterNum())){
                BssTaxinfo purchaserTaxInfo = new BssTaxinfo();
                BssTaxinfo taxNo = bssTaxinfoService.getByTaxNo(wordsResult.getPurchaserRegisterNum());
                if(taxNo == null){
                    //购买方
                    purchaserTaxInfo.setName(wordsResult.getPurchaserName());
                    purchaserTaxInfo.setTaxNo(wordsResult.getPurchaserRegisterNum());
                    purchaserTaxInfo.setAccount(wordsResult.getPurchaserBank());
                    purchaserTaxInfo.setAddressPhone(wordsResult.getPurchaserAddress());
                    purchaserTaxInfo.setPlatformId(bssplatformId);
                    bssTaxinfoService.save(purchaserTaxInfo);
                    vatInvoice.setBuyTaxInfoId(purchaserTaxInfo.getId());
                }else{
                    vatInvoice.setBuyTaxInfoId(taxNo.getId());
                }
            }

            //商品
            List<BssGoods> goods = new ArrayList<>();
            List<CommodityName> commodityNames = wordsResult.getCommodityName();
            List<CommodityType> commodityTypes = wordsResult.getCommodityType();
            List<CommodityUnit> commodityUnits = wordsResult.getCommodityUnit();
            List<CommodityNum> commodityNums = wordsResult.getCommodityNum();
            List<CommodityPrice> commodityPrices = wordsResult.getCommodityPrice();
            List<CommodityAmount> commodityAmounts = wordsResult.getCommodityAmount();
            List<CommodityTaxRate> commodityTaxRates = wordsResult.getCommodityTaxRate();
            List<CommodityTax> commodityTaxs = wordsResult.getCommodityTax();

            for (int i = 0; i < commodityNames.size(); i++) {
                BssGoods good = new BssGoods();
                good.setName(commodityNames.get(i).getWord());
                if (ToolUtil.checkListSize(commodityTypes) && commodityTypes.size() > i && !StringUtil.isBlank(commodityTypes.get(i).getWord())) {
                    good.setSpecification(commodityTypes.get(i).getWord());
                }
                if (ToolUtil.checkListSize(commodityUnits) && commodityUnits.size() > i && !StringUtil.isBlank(commodityUnits.get(i).getWord())) {
                    good.setUnit(commodityUnits.get(i).getWord());
                }
                if (ToolUtil.checkListSize(commodityNums) && !StringUtil.isBlank(commodityNums.get(i).getWord())) {
                    good.setNum(Double.valueOf(commodityNums.get(i).getWord()));
                }
                if (ToolUtil.checkListSize(commodityPrices) && commodityPrices.size() > i && !StringUtil.isBlank(commodityPrices.get(i).getWord())) {
                    good.setUnitPrice(commodityPrices.get(i).getWord());
                }
                if (ToolUtil.checkListSize(commodityAmounts) && !StringUtil.isBlank(commodityAmounts.get(i).getWord())) {
                    good.setDetailAmount(new BigDecimal(commodityAmounts.get(i).getWord()));
                }
                if (ToolUtil.checkListSize(commodityTaxRates) && !StringUtil.isBlank(commodityTaxRates.get(i).getWord())) {
                    good.setTaxRate(commodityTaxRates.get(i).getWord());
                }
                if (ToolUtil.checkListSize(commodityTaxs) && !StringUtil.isBlank(commodityTaxs.get(i).getWord())) {
                    good.setGoodTaxAmount(new BigDecimal(commodityTaxs.get(i).getWord()));
                }
                goods.add(good);
            }

            vatInvoice.setInvoiceCode(wordsResult.getInvoiceCode());
            vatInvoice.setInvoiceNo(wordsResult.getInvoiceNum());
            vatInvoice.setInvoiceDate(wordsResult.getInvoiceDate());
            vatInvoice.setCheckCode(wordsResult.getCheckCode());
            vatInvoice.setInvoiceMoney(new BigDecimal(wordsResult.getTotalAmount()));
            vatInvoice.setTaxAmount(new BigDecimal(wordsResult.getTotalTax()));
            vatInvoice.setTotalAmount(new BigDecimal(wordsResult.getAmountInFiguers()));
            vatInvoice.setTotalAmountCn(wordsResult.getAmountInWords());
            vatInvoice.setRemark(wordsResult.getRemarks());
            vatInvoice.setBssGoods(goods);
            vatInvoice.setInvoiceImg(upload.getPath());
            vatInvoice.setInvoiceType(VatInvoiceTypeEnum.getVatInvoiceCode(wordsResult.getInvoiceType()));

            return ResultVoUtil.success(vatInvoice);
        } catch (Exception e) {
            return ResultVoUtil.error("上传图片失败");
        }
    }
}