package cn.superdesk.uniorder.controller.organisation;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import cn.superdesk.uniorder.common.exception.constants.ExceptionMsg;
import cn.superdesk.uniorder.common.numerical.AnStringUtils;
import cn.superdesk.uniorder.common.pagination.PageQueryGenericParam;
import cn.superdesk.uniorder.common.pagination.PageQueryParam;
import cn.superdesk.uniorder.common.rest.response.R;
import cn.superdesk.uniorder.common.rest.response.ResponseResultOuterUtils;
import cn.superdesk.uniorder.controller.base.BaseController;
import cn.superdesk.uniorder.dao.entity.organisation.SysEnterpriseExtInvoice;
import cn.superdesk.uniorder.dto.param.organisation.SysCliqueXInvoiceCriteria;
import cn.superdesk.uniorder.dto.param.organisation.SysEnterpriseExtInvoiceParam;
import cn.superdesk.uniorder.dto.param.organisation.SysEnterpriseExtInvoiceQueryCriteria;
import cn.superdesk.uniorder.dto.param.organisation.SysEnterpriseExtInvoiceXCliqueParam;
import cn.superdesk.uniorder.dto.vo.organisation.SysEnterpriseExtInvoiceExtPathVo;
import cn.superdesk.uniorder.dubbo.consumer.organisation.SysCliqueXInvoiceDubboConsumerService;
import cn.superdesk.uniorder.dubbo.consumer.organisation.SysEnterpriseExtInvoiceDubboConsumerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;


/**
 * @Description: 系统管理-企业信息-扩展-发票相关
 * @Author: linjinyu
 * @Email linjinyu@avic-s.com
 * @CreateDate: 2020-08-20 19:16:09
 * @UpdateUser: linjinyu
 * @UpdateDate: 2020-08-20 19:16:09
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Api(value = "企业信息-扩展-发票相关", tags = {"企业信息-扩展-发票相关"})
@Slf4j
@RestController
@RequestMapping("/sysEnterpriseExtInvoice")
public class SysEnterpriseExtInvoiceController extends BaseController {

    @Autowired
    private SysEnterpriseExtInvoiceDubboConsumerService sysEnterpriseExtInvoiceDubboConsumerService;
    @Autowired
    private SysCliqueXInvoiceDubboConsumerService sysCliqueXInvoiceDubboConsumerService;

    @ApiOperation(value = "分页查询 conditions.outVirtId")
    @RequestMapping(value = "list", method = RequestMethod.POST)
    @ResponseBody
    public R<List<SysEnterpriseExtInvoiceExtPathVo>> pageQuerySysEnterpriseExtInvoices(@RequestBody SysEnterpriseExtInvoiceQueryCriteria queryCriteria) {

        log.info("pageQuerySysEnterpriseExtInvoice:\n{}", JSONUtil.toJsonStr(queryCriteria));

        R<List<SysEnterpriseExtInvoiceExtPathVo>> result = new R<>();

        // TODO 参数合法性判定

        result = sysEnterpriseExtInvoiceDubboConsumerService.pageQuery(queryCriteria, getToken());

        return result;
    }

//	@ApiOperation(value = "分页查询 conditions.outVirtId")
//	@RequestMapping(value = "list", method = RequestMethod.POST)
//	@ResponseBody
//	public R<List<SysEnterpriseExtInvoice>> pageQuerySysEnterpriseExtInvoices(@RequestBody PageQueryParam param) {
//
//		log.info("pageQuerySysEnterpriseExtInvoice:\n{}", JSONUtil.toJsonStr(param));
//
//		R<List<SysEnterpriseExtInvoice>> result = new R<>();
//
//		// TODO 参数合法性判定
//
//		result = sysEnterpriseExtInvoiceDubboConsumerService.pageQuery(param.getConditions(), param.getPageNo(), param.getPageSize());
//
//		return result;
//	}

    /**
     * http://192.168.6.223:8089/web/sysEnterpriseExtInvoice/tree
     * 返回发票抬头信息
     *
     * @param param
     * @return
     */
    @ApiOperation(value = "树型查询 conditions.outVirtId")
    @RequestMapping(value = "tree", method = RequestMethod.POST)
    @ResponseBody
    public R<List<SysEnterpriseExtInvoiceExtPathVo>> treeQuerySysEnterpriseExtInvoices(@RequestBody PageQueryGenericParam<SysCliqueXInvoiceCriteria> param) {

        log.info("pageQuerySysEnterpriseExtInvoice:\n{}", JSONUtil.toJsonStr(param));

        R<List<SysEnterpriseExtInvoiceExtPathVo>> result = new R<>();

        // TODO 参数合法性判定

        result = sysEnterpriseExtInvoiceDubboConsumerService.pageQuerySysCliqueXInvoice(param.getConditions(), param.getPageNo(), param.getPageSize());

        return result;
    }

    @ApiOperation(value = "按id查询")
    @RequestMapping(value = "{id}", method = RequestMethod.GET)
    @ResponseBody
    public R<List<SysEnterpriseExtInvoice>> getById(@PathVariable("id") long id) {

        R<List<SysEnterpriseExtInvoice>> result = new R<>();

        // TODO 参数合法性判定

//		SysEnterpriseExtInvoice entity = sysEnterpriseExtInvoiceDubboConsumerService.findSysEnterpriseExtInvoiceById(id);
        SysEnterpriseExtInvoice entity = sysEnterpriseExtInvoiceDubboConsumerService.findById(id);

        if (null == entity) {
            result.setSuccess(false);
            result.setMessage(ExceptionMsg.RECORD_NOT_EXIST.getMsg());
        } else {
            List<SysEnterpriseExtInvoice> data = new ArrayList<>();
            data.add(entity);
            result.setData(data);
        }

        return result;
    }

    @ApiOperation(value = "op设置默认-会取消之前默认的")
    @RequestMapping(value = "set/default/{sysEnterpriseExtInvoiceId}", method = RequestMethod.GET)
    @ResponseBody
    public R<String> opSetDefault(@PathVariable("sysEnterpriseExtInvoiceId") long sysEnterpriseExtInvoiceId) {

        // TODO 参数合法性判定
        SysEnterpriseExtInvoice entity = sysEnterpriseExtInvoiceDubboConsumerService.findById(sysEnterpriseExtInvoiceId);

        if (ObjectUtil.isEmpty(entity)) {
            return ResponseResultOuterUtils.createErrorResult("500", "非法操作");
        }

        log.info("设置默认-会取消之前默认的 {}", JSONUtil.toJsonPrettyStr(entity));

        int ret = sysEnterpriseExtInvoiceDubboConsumerService.opSetDefault(entity, getToken());

        if (ret > 0) {
            return ResponseResultOuterUtils.createSuccesResult();
        } else {
            return ResponseResultOuterUtils.createErrorResult("500", "操作失败");
        }
    }

    @ApiOperation(value = "op取消默认")
    @RequestMapping(value = "set/normal/{sysEnterpriseExtInvoiceId}", method = RequestMethod.GET)
    @ResponseBody
    public R<String> opSetNormal(@PathVariable("sysEnterpriseExtInvoiceId") long sysEnterpriseExtInvoiceId) {

        // TODO 参数合法性判定
        SysEnterpriseExtInvoice entity = sysEnterpriseExtInvoiceDubboConsumerService.findById(sysEnterpriseExtInvoiceId);

        if (ObjectUtil.isEmpty(entity)) {
            return ResponseResultOuterUtils.createErrorResult("500", "非法操作");
        }

        log.info("取消默认-{}", JSONUtil.toJsonPrettyStr(entity));

        int ret = sysEnterpriseExtInvoiceDubboConsumerService.opSetNormal(entity, getToken());

        if (ret > 0) {
            return ResponseResultOuterUtils.createSuccesResult();
        } else {
            return ResponseResultOuterUtils.createErrorResult("500", "操作失败");
        }
    }

    @ApiOperation(value = "发票抬头名称重复,请重新输入")
    @RequestMapping(value = "getByCompanyName", method = RequestMethod.POST)
    @ResponseBody
    public R<SysEnterpriseExtInvoice> getByCompanyName(@RequestBody SysEnterpriseExtInvoiceParam param) {

        log.info("getByCompanyName:\n{}", JSONUtil.toJsonStr(param));


        // TODO 参数合法性判定

        SysEnterpriseExtInvoice sysEnterpriseExtInvoice = sysEnterpriseExtInvoiceDubboConsumerService.getByCompanyName(param.getCompanyName());


        return ResponseResultOuterUtils.createSuccesResult("发票抬头名称重复,请重新输入", sysEnterpriseExtInvoice);
    }

    @ApiOperation(value = "新增发票抬头(已添加 发票抬头重复较验)")
    @RequestMapping(value = "add", method = RequestMethod.POST)
    @ResponseBody
    public R<String> addSysEnterpriseExtInvoice(@RequestBody SysEnterpriseExtInvoiceParam param) {

        log.info("addSysEnterpriseExtInvoice:\n{}", JSONUtil.toJsonStr(param));


        // TODO 参数合法性判定

//		【结算中心,企业管理-发票信息设置,发票抬头名称内容调整为开票抬头可全局重复。】 https://www.tapd.cn/33003868/prong/stories/view/1133003868001003884
//		SysEnterpriseExtInvoice sysEnterpriseExtInvoice = sysEnterpriseExtInvoiceDubboConsumerService.getByCompanyName(param.getCompanyName());
//
//		if (ObjectUtil.isNotNull(sysEnterpriseExtInvoice)) {
//			return ResponseResultOuterUtils.createErrorResult("500", "发票抬头名称重复,请重新输入");
//		}

        sysEnterpriseExtInvoiceDubboConsumerService.addSysEnterpriseExtInvoice(param, getToken());

        return new R<>("200", "操作成功", true);
    }

    @ApiOperation(value = "更新发票抬头")
    @RequestMapping(value = "update", method = RequestMethod.POST)
    @ResponseBody
    public R<String> updateSysEnterpriseExtInvoice(@RequestBody SysEnterpriseExtInvoiceParam param) {

        log.info("updateSysEnterpriseExtInvoice:\n{}", JSONUtil.toJsonStr(param));

        sysEnterpriseExtInvoiceDubboConsumerService.updateSysEnterpriseExtInvoice(param, getToken());

        return new R<>("200", "操作成功", true);
    }


    @ApiOperation(value = "新增发票抬头X集团")
    @RequestMapping(value = "addSysEnterpriseExtInvoiceXCliqueParam", method = RequestMethod.POST)
    @ResponseBody
    public R<String> addSysEnterpriseExtInvoiceXCliqueParam(@RequestBody SysEnterpriseExtInvoiceXCliqueParam param) {

        log.info("addSysEnterpriseExtInvoiceXCliqueParam:\n{}", JSONUtil.toJsonStr(param));


        // TODO 参数合法性判定

//		sysEnterpriseExtInvoiceDubboConsumerService.addSysEnterpriseExtInvoice(param.getInvoice());
//
//
//		param.getPath().forEach(str ->{
//			SysCliqueXInvoiceParam sysCliqueXInvoiceParam = new SysCliqueXInvoiceParam();
//			sysCliqueXInvoiceParam.setPath();
//			SysCliqueXInvoiceParam.setSysEnterpriseExtInvoiceId();
//			sysCliqueXInvoiceDubboConsumerService.addSysCliqueXInvoice(sysCliqueXInvoiceParam);
//		});

        sysEnterpriseExtInvoiceDubboConsumerService.addSysEnterpriseExtInvoiceXCliqueParam(param, getToken());


        return new R<>("200", "操作成功", true);
    }


    @ApiOperation(value = "更新发票抬头X集团")
    @RequestMapping(value = "updateSysEnterpriseExtInvoiceXCliqueParam", method = RequestMethod.POST)
    @ResponseBody
    public R<String> updateSysEnterpriseExtInvoiceXCliqueParam(@RequestBody SysEnterpriseExtInvoiceXCliqueParam param) {

        log.info("updateSysEnterpriseExtInvoiceXCliqueParam:\n{}", JSONUtil.toJsonStr(param));

        sysEnterpriseExtInvoiceDubboConsumerService.updateSysEnterpriseExtInvoiceXCliqueParam(param, getToken());

        return new R<>("200", "操作成功", true);
    }

    @ApiOperation(value = "删除")
    @RequestMapping(value = "delete/{id}", method = RequestMethod.POST)
    @ResponseBody
    public R<String> deleteSysEnterpriseExtInvoice(@PathVariable("id") long id) {

        // TODO 参数合法性判定

        sysEnterpriseExtInvoiceDubboConsumerService.deleteSysEnterpriseExtInvoice(id, getToken());

        return new R<>("200", "操作成功", true);
    }

    @ApiOperation(value = "批量删除")
    @RequestMapping(value = "delete_ids", method = RequestMethod.POST)
    @ResponseBody
    public R<String> deleteIdsSysEnterpriseExtInvoice(@RequestParam(value = "ids") long[] ids) {

        log.info(JSONUtil.toJsonStr(ids));

        for (long id : ids) {
            sysEnterpriseExtInvoiceDubboConsumerService.deleteSysEnterpriseExtInvoice(id, getToken());
        }

        return new R<>("200", "操作成功", true);

    }


    /****************************************** 购方主体-缓存 start ******************************************/

    /**
     * http://192.168.6.223:8089/web/sysEnterpriseExtInvoice/cacheInit
     *
     * @return
     */
    @ApiOperation(value = "cacheInit")
    @RequestMapping(value = "cacheInit", method = RequestMethod.POST)
    @ResponseBody
    public R<String> cacheInit() {

        sysEnterpriseExtInvoiceDubboConsumerService.cacheInit();
        return new R<>("200", "操作成功", true);

    }

    @ApiOperation(value = "cacheRefresh")
    @RequestMapping(value = "cacheRefresh", method = RequestMethod.POST)
    @ResponseBody
    public R<String> cacheRefresh() {

        sysEnterpriseExtInvoiceDubboConsumerService.cacheRefresh();
        return new R<>("200", "操作成功", true);

    }

    @ApiOperation(value = "cacheRemove")
    @RequestMapping(value = "cacheRemove", method = RequestMethod.POST)
    @ResponseBody
    public R<String> cacheRemove() {

        sysEnterpriseExtInvoiceDubboConsumerService.cacheRemove();
        return new R<>("200", "操作成功", true);

    }


    /**
     * hashtable relation:sys_enterprise_ext_invoice:company_name field 中航物业管理有限公司济南分公司
     * <p>
     * {
     * "conditions": {
     * "hashTable": "relation:sys_enterprise_ext_invoice:company_name",
     * "keyField": "中航物业管理有限公司长沙分公司"
     * }
     * }
     *
     * @return
     */
    @ApiOperation(value = "cacheGet")
    @RequestMapping(value = "cacheGet", method = RequestMethod.POST)
    @ResponseBody
    public R<String> cacheGet(@RequestBody PageQueryParam param) {

//		String hashTable = "relation:sys_enterprise_ext_invoice:company_name";
//		String keyField = "中航物业管理有限公司";

        String hashTable = AnStringUtils.getString(param.getConditions().get("hashTable"));
        String keyField = AnStringUtils.getString(param.getConditions().get("keyField"));

        log.info("{}{}", hashTable, keyField);

        String responseData = sysEnterpriseExtInvoiceDubboConsumerService.cacheGet(hashTable, keyField);
        return new R<>("200", "操作成功", responseData);

    }

    /****************************************** 购方主体-缓存   end ******************************************/


}
