package com.hzs.sale.unit.controller.manage;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzs.common.core.constant.msg.WaresMsgConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.ETransactionKey;
import com.hzs.common.core.enums.EYesNo;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.utils.TransactionUtils;
import com.hzs.common.core.utils.poi.ExcelUtil;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.core.web.page.TableDataInfo;
import com.hzs.common.domain.sale.product.BdProduct;
import com.hzs.common.domain.sale.wares.BdUnit;
import com.hzs.common.security.service.UserTokenService;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.sale.product.service.IBdProductService;
import com.hzs.sale.unit.param.UnitParam;
import com.hzs.sale.unit.service.IBdUnitService;
import com.hzs.system.base.ITransactionServiceApi;
import com.hzs.system.sys.dto.LoginUser;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.List;

/**
 * @BelongsProject: hzs_cloud
 * @BelongsPackage: com.hzs.sale.unit.controller.manage
 * @Author: yh
 * @CreateTime: 2023-03-11  11:25
 * @Description:
 * @Version: 1.0
 */
@RestController
@RequestMapping("/manage/unit")
public class UnitController extends BaseController {
    @Autowired
    private IBdProductService productService;
    @Autowired
    private UserTokenService userTokenService;
    @DubboReference
    private ITransactionServiceApi transactionServiceApi;
    @Autowired
    private IBdUnitService unitService;

    /**
     * 单位列表
     *
     * @return
     */
    @GetMapping("list")
    public TableDataInfo list(UnitParam unit) {
        startPage();
        QueryWrapper<BdUnit> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(unit.getName())) {
            queryWrapper.like("NAME", unit.getName());
        }
        if (unit.getStartDate() != null && unit.getEndDate() != null) {
            queryWrapper.between("CREATION_TIME", unit.getStartDate(), unit.getEndDate());
        }
        queryWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        queryWrapper.orderByDesc("SORT");
        List<BdUnit> list = unitService.list(queryWrapper);
        return getDataTable(list);
    }

    /**
     * 新增单位
     *
     * @param unit
     * @return
     */
    @PostMapping("save")
    public AjaxResult save(@RequestBody BdUnit unit) {
        if (unit.getSort() == null) {
            return AjaxResult.error(TransactionUtils.getContent(WaresMsgConstants.SORT_IS_NOT_NULL));
        }
        QueryWrapper<BdUnit> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("SORT", unit.getSort());
        queryWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        int count = unitService.count(queryWrapper);
        if (count > 0) {
            return AjaxResult.error(TransactionUtils.getContent(WaresMsgConstants.SORT_DUPLICATES));
        }
        // 查询单位名称是否重复
        QueryWrapper<BdUnit> wrapper = new QueryWrapper<>();
        wrapper.eq("NAME", unit.getName());
        wrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        int unitCount = unitService.count(wrapper);
        if (unitCount > 0) {
            return AjaxResult.error(TransactionUtils.getContent(WaresMsgConstants.NAME_DUPLICATES));
        }
        unit.setPkCreator(SecurityUtils.getUserId());
        unit.setPkCountry(SecurityUtils.getPkCountry());
        unit.setCreationTime(DateUtils.currentDateTime());
        LoginUser user = userTokenService.getLoginUser();
        R<Integer> transaction = transactionServiceApi.createTransaction(user.getDataCountry(), ETransactionKey.UNIT, unit.getName(), EYesNo.NO, EYesNo.NO);
        unit.setPkTransaction(transaction.getData());
        unitService.save(unit);
        return AjaxResult.success();
    }

    /**
     * 修改单位
     *
     * @param unit
     * @return
     */
    @PostMapping("update")
    public AjaxResult update(@RequestBody BdUnit unit) {
        if (unit.getSort() == null) {
            return AjaxResult.error(TransactionUtils.getContent(WaresMsgConstants.SORT_IS_NOT_NULL));
        }
        QueryWrapper<BdUnit> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("SORT", unit.getSort());
        queryWrapper.notIn("PK_ID", unit.getPkId());
        int count = unitService.count(queryWrapper);
        if (count > 0) {
            return AjaxResult.error(TransactionUtils.getContent(WaresMsgConstants.SORT_DUPLICATES));
        }
        // 查询单位名称是否重复
        QueryWrapper<BdUnit> wrapper = new QueryWrapper<>();
        wrapper.eq("NAME", unit.getName());
        wrapper.notIn("PK_ID", unit.getPkId());
        int unitCount = unitService.count(wrapper);
        if (unitCount > 0) {
            return AjaxResult.error(TransactionUtils.getContent(WaresMsgConstants.NAME_DUPLICATES));
        }
        unit.setPkModified(SecurityUtils.getUserId());
        unit.setModifiedTime(DateUtils.currentDateTime());
        BdUnit unt = unitService.getById(unit.getPkId());
        if (unt.getPkTransaction() != null) {
            transactionServiceApi.updateTransaction(SecurityUtils.getPkCountry(), unit.getName(), unt.getPkTransaction(), true);
        }
        unitService.updateById(unit);
        return AjaxResult.success();
    }

    /**
     * 查询详情
     *
     * @param pkId
     * @return
     */
    @GetMapping("detail")
    public AjaxResult detail(Long pkId) {
        return AjaxResult.success(unitService.getById(pkId));
    }

    /**
     * 删除单位
     *
     * @param pkId
     * @return
     */
    @DeleteMapping("/{pkId}")
    public AjaxResult remove(@PathVariable Integer pkId) {
        // 删除翻译
        BdUnit unit = unitService.getById(pkId);
        QueryWrapper<BdProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("UNIT", pkId);
        int count = productService.count(queryWrapper);
        // 产品单位已被使用无法删除
        if (count > 0) {
            return AjaxResult.error(TransactionUtils.getContent(WaresMsgConstants.UNIT_HAS_BEEN_USED));
        }
        unitService.removeById(pkId);

        transactionServiceApi.removeTransactionByPkId(Collections.singletonList(unit.getPkTransaction().longValue()));
        return AjaxResult.success();
    }

    /**
     * 查询全部单位
     *
     * @return
     */
    @GetMapping("find-all")
    public AjaxResult findAll() {
        QueryWrapper<BdUnit> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        return AjaxResult.success(unitService.list(queryWrapper));
    }

    /**
     * 单位列表导出
     *
     * @return
     */
    @PostMapping("export")
    public void export(UnitParam unit, HttpServletResponse response) {

        QueryWrapper<BdUnit> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(unit.getName())) {
            queryWrapper.like("NAME", unit.getName());
        }
        if (unit.getStartDate() != null && unit.getEndDate() != null) {
            queryWrapper.between("CREATION_TIME", unit.getStartDate(), unit.getEndDate());
        }
        queryWrapper.eq("PK_COUNTRY", SecurityUtils.getPkCountry());
        queryWrapper.orderByDesc("SORT");
        List<BdUnit> list = unitService.list(queryWrapper);
        ExcelUtil<BdUnit> util = new ExcelUtil<BdUnit>(BdUnit.class);
        util.exportExcel(response, list, "单位导出");
    }

}
