package com.hzs.system.base.controller.manage;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.msg.ConfigMsgConstants;
import com.hzs.common.core.enums.EOperationBusiness;
import com.hzs.common.core.enums.EOperationMethod;
import com.hzs.common.core.enums.EOperationModule;
import com.hzs.common.core.utils.RandomNumberGenerator;
import com.hzs.common.core.utils.StringUtils;
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.system.base.BdArea;
import com.hzs.common.domain.system.base.BdStorehouse;
import com.hzs.common.domain.system.base.BdStorehouseAreaMiddle;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.core.utils.TransactionUtils;
import com.hzs.system.base.service.IBdAreaService;
import com.hzs.system.base.service.IBdStorehouseAreaMiddleService;
import com.hzs.system.base.service.IBdStorehouseService;
import com.hzs.system.base.vo.BdStorehouseAreaMiddleVO;
import com.hzs.system.base.vo.BdStorehouseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 仓库配置前端控制器
 * </p>
 *
 * @author hzs
 * @since 2022-08-02
 */
@Slf4j
@RestController
@RequestMapping("/manage/storehouse")
public class BdStorehouseController extends BaseController {

    @Autowired
    private IBdStorehouseService iBdStorehouseService;
    @Autowired
    private IBdStorehouseAreaMiddleService iBdStorehouseAreaMiddleService;
    @Autowired
    private IBdAreaService areaService;


    /**
     * 获取仓库列表
     */
    @Log(module = EOperationModule.STOREHOUSE, business = EOperationBusiness.STOREHOUSE, method = EOperationMethod.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(BdStorehouseVO bdStorehouse) {
        startPage();
        bdStorehouse.setPkCountry(SecurityUtils.getPkCountry());
        List<BdStorehouseVO> list = iBdStorehouseService.selectBdStorehouseList(bdStorehouse);
        list.forEach(itm -> {
            BdStorehouseAreaMiddleVO sam = new BdStorehouseAreaMiddleVO();
            sam.setPkStorehouse(itm.getPkId());
            List<BdStorehouseAreaMiddleVO> samList = iBdStorehouseAreaMiddleService.getBdStorehouseAreaMiddleList(sam);
            itm.setSamList(samList);
        });
        return getDataTable(list);
    }

    /**
     * 获取仓库列表下拉选
     */
    @Log(module = EOperationModule.STOREHOUSE, business = EOperationBusiness.STOREHOUSE, method = EOperationMethod.SELECT)
    @GetMapping("/list-nopag")
    public TableDataInfo listNoPag(BdStorehouseVO bdStorehouse) {
        bdStorehouse.setPkCountry(SecurityUtils.getPkCountry());
        List<BdStorehouseVO> list = iBdStorehouseService.selectBdStorehouseList(bdStorehouse);
        return getDataTable(list);
    }

    /**
     * 获取仓库列表下拉选
     */
    @GetMapping("/refer")
    public TableDataInfo referStorehouse(BdStorehouseVO bdStorehouse) {
        if(bdStorehouse.getPkCorp() == null){
            return getDataTable(null);
        }
        if(bdStorehouse.getPkCountry() == null) {
            bdStorehouse.setPkCountry(SecurityUtils.getPkCountry());
        }
        List<BdStorehouseVO> list = iBdStorehouseService.selectBdStorehouseList(bdStorehouse);
        return getDataTable(list);
    }

    /**
     * 获取单条仓库信息
     *
     * @param pkId
     * @return
     */
    @Log(module = EOperationModule.STOREHOUSE, business = EOperationBusiness.STOREHOUSE, method = EOperationMethod.SELECT)
    @GetMapping("/getBdStorehouse/{pkId}")
    public AjaxResult getBdStorehouse(@PathVariable Integer pkId) {
        BdStorehouse bdStorehouse = new BdStorehouse();
        bdStorehouse.setPkId(pkId);
        BdStorehouse bdStorehouseResult = iBdStorehouseService.getBdStorehouse(bdStorehouse);
        BdStorehouseVO storehouseVO = BeanUtil.copyProperties(bdStorehouseResult, BdStorehouseVO.class);
        BdStorehouseAreaMiddleVO sam = new BdStorehouseAreaMiddleVO();
        sam.setPkStorehouse(storehouseVO.getPkId());
        List<BdStorehouseAreaMiddleVO> samList = iBdStorehouseAreaMiddleService.getBdStorehouseAreaMiddleList(sam);
        List<Integer> provinceList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(samList)) {
            samList.forEach(itm -> provinceList.add(itm.getProvince()));
        }
        storehouseVO.setProvinceList(provinceList);
        storehouseVO.setSamList(samList);
        return AjaxResult.success(storehouseVO);
    }

    /**
     * 仓库列表导出
     *
     * @param response
     * @param bdStorehouse
     */
    @Log(module = EOperationModule.STOREHOUSE, business = EOperationBusiness.STOREHOUSE, method = EOperationMethod.SELECT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BdStorehouseVO bdStorehouse) {
        List<BdStorehouseVO> list = iBdStorehouseService.selectBdStorehouseList(bdStorehouse);
        ExcelUtil<BdStorehouseVO> util = new ExcelUtil<>(BdStorehouseVO.class);
        util.exportExcel(response, list, "仓库列表数据");
    }

    /**
     * @description: 生成仓库编号
     * @author: zhang jing
     * @date: 2023/5/5 10:41
     * @param: []
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.STOREHOUSE, business = EOperationBusiness.STOREHOUSE, method = EOperationMethod.SELECT)
    @GetMapping("/getCode")
    public AjaxResult getCode() {
        QueryWrapper<BdStorehouse> queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("CREATION_TIME");
        List<BdStorehouse> storehouse = iBdStorehouseService.list(queryWrapper);
        String code = "";
        if (CollectionUtil.isNotEmpty(storehouse)) {
            code = RandomNumberGenerator.getNextNumber(storehouse.get(0).getCode(), 2);
        } else {
            code = RandomNumberGenerator.getNextNumber("ST00000001", 2);
        }
        return AjaxResult.success(code);
    }

    /**
     * 新增仓库信息
     *
     * @param bdStorehouse
     * @return
     */
    @Log(module = EOperationModule.STOREHOUSE, business = EOperationBusiness.STOREHOUSE, method = EOperationMethod.INSERT)
    @PostMapping("/save")
    public AjaxResult save(@RequestBody BdStorehouseVO bdStorehouse) {
        if (StringUtils.isEmpty(bdStorehouse.getCode())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.STOREHOUSE_CODE_NOT_NULL));
        }
        if (StringUtils.isEmpty(bdStorehouse.getName())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.STOREHOUSE_NAME_NOT_NULL));
        }
        if (StringUtils.isNull(bdStorehouse.getProvince())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.GLO_PROVINCE_NOT_NULL));
        }
        if (StringUtils.isEmpty(bdStorehouse.getWareAddress())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.HO_ADDRESS_NOT_NULL));
        }
        if (StringUtils.isEmpty(bdStorehouse.getContacts())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.CONTACTS_NOT_NULL));
        }
        if (StringUtils.isEmpty(bdStorehouse.getMobilePhone())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MOBILEPHONE_NOT_NULL));
        }
        if (CollectionUtil.isEmpty(bdStorehouse.getProvinceList())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.STOREHOUSE_PROVINCE_NOT_NULL));
        }
        BdStorehouse bdStorehouseCheck = new BdStorehouse();
        bdStorehouseCheck.setCode(bdStorehouse.getCode());
        bdStorehouseCheck = iBdStorehouseService.getBdStorehouse(bdStorehouseCheck);
        if (bdStorehouseCheck != null) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.STOREHOUSE_CODE_REPEAT));
        }
        for (Integer pr : bdStorehouse.getProvinceList()) {
            QueryWrapper<BdStorehouseAreaMiddle> queryWrapper = new QueryWrapper();
            queryWrapper.eq("PROVINCE", pr);
            List<BdStorehouseAreaMiddle> list = iBdStorehouseAreaMiddleService.list(queryWrapper);
            if (CollectionUtil.isNotEmpty(list)) {
                BdArea ar = areaService.getById(pr);
                return AjaxResult.error(ar.getName() + TransactionUtils.getContent(ConfigMsgConstants.AREA_BINDING_REPEAT));
            }
        }
        bdStorehouse.setPkCreator(SecurityUtils.getUserId());
        bdStorehouse.setCreationTime(new Date());
        bdStorehouse.setPkCountry(SecurityUtils.getPkCountry());
        return toAjax(iBdStorehouseService.intBdStorehouse(bdStorehouse));
    }


    /**
     * 修改保存仓库信息
     *
     * @param bdStorehouse
     * @return
     */
    @Log(module = EOperationModule.STOREHOUSE, business = EOperationBusiness.STOREHOUSE, method = EOperationMethod.UPDATE)
    @PostMapping("/update")
    public AjaxResult update(@RequestBody BdStorehouseVO bdStorehouse) {
        if (StringUtils.isEmpty(bdStorehouse.getCode())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.STOREHOUSE_CODE_NOT_NULL));
        }
        if (StringUtils.isEmpty(bdStorehouse.getName())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.STOREHOUSE_NAME_NOT_NULL));
        }
        if (StringUtils.isNull(bdStorehouse.getProvince())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.GLO_PROVINCE_NOT_NULL));
        }
        if (StringUtils.isEmpty(bdStorehouse.getWareAddress())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.HO_ADDRESS_NOT_NULL));
        }
        if (StringUtils.isEmpty(bdStorehouse.getContacts())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.CONTACTS_NOT_NULL));
        }
        if (StringUtils.isEmpty(bdStorehouse.getMobilePhone())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MOBILEPHONE_NOT_NULL));
        }
        if (CollectionUtil.isEmpty(bdStorehouse.getProvinceList())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.HO_REGION_NOT_NULL));
        }
        BdStorehouse bdStorehouseCheck = new BdStorehouse();
        bdStorehouseCheck.setCode(bdStorehouse.getCode());
        bdStorehouseCheck.setPkId(bdStorehouse.getPkId());
        bdStorehouseCheck = iBdStorehouseService.checkBdStorehouse(bdStorehouseCheck);
        if (bdStorehouseCheck != null) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.STOREHOUSE_CODE_REPEAT));
        }
        for (Integer pr : bdStorehouse.getProvinceList()) {
            QueryWrapper<BdStorehouseAreaMiddle> queryWrapper = new QueryWrapper();
            queryWrapper.eq("PROVINCE", pr);
            queryWrapper.ne("PK_STOREHOUSE",bdStorehouse.getPkId());
            List<BdStorehouseAreaMiddle> list = iBdStorehouseAreaMiddleService.list(queryWrapper);
            if (CollectionUtil.isNotEmpty(list)) {
                BdArea ar = areaService.getById(pr);
                return AjaxResult.error(ar.getName() + TransactionUtils.getContent(ConfigMsgConstants.AREA_BINDING_REPEAT));
            }
        }

        bdStorehouse.setPkModified(SecurityUtils.getUserId());
        bdStorehouse.setModifiedTime(new Date());
        bdStorehouse.setPkCountry(SecurityUtils.getPkCountry());
        return AjaxResult.success(iBdStorehouseService.updateBdStorehouse(bdStorehouse));
    }

    /**
     * 删除仓库信息
     *
     * @param pkId
     * @return
     */
    @Log(module = EOperationModule.STOREHOUSE, business = EOperationBusiness.STOREHOUSE, method = EOperationMethod.DELETE)
    @PostMapping("/delBdStorehouse/{pkId}")
    public AjaxResult delBdStorehouse(@PathVariable Long pkId) {
        BdStorehouseVO bdStorehouse=new BdStorehouseVO ();
        bdStorehouse.setPkId(pkId.intValue());
        bdStorehouse.setPkModified(SecurityUtils.getUserId());
        bdStorehouse.setModifiedTime(new Date());
        bdStorehouse.setPkCountry(SecurityUtils.getPkCountry());
        return toAjax(iBdStorehouseService.delBdStorehouse(bdStorehouse));
    }
}
