package cn.ezhizao.project.business.supplier.controller;

import cn.ezhizao.common.utils.SecurityUtils;
import cn.ezhizao.framework.aspectj.lang.annotation.Log;
import cn.ezhizao.framework.aspectj.lang.enums.BusinessType;
import cn.ezhizao.framework.web.controller.BaseController;
import cn.ezhizao.framework.web.domain.AjaxResult;
import cn.ezhizao.framework.web.page.TableDataInfo;
import cn.ezhizao.project.business.outsourceBalanceAccount.domain.BizOutsourceBalanceAccount;
import cn.ezhizao.project.business.outsourceBalanceAccount.service.IBizOutsourceBalanceAccountService;
import cn.ezhizao.project.business.supplier.domain.*;
import cn.ezhizao.project.business.supplier.service.*;
import cn.ezhizao.project.system.domain.SysDept;
import cn.ezhizao.project.system.service.ISysConfigService;
import cn.ezhizao.project.system.service.ISysDeptService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 供应商 biz_supplier
 *
 * @author ezhizao
 * date    2024-04-24
 */
@RestController
@RequestMapping("/business/supplier")
public class BizSupplierController extends BaseController {
    @Resource
    private IBizSupplierService iBizSupplierService;
    @Resource
    private IBizSupplierProductService iBizSupplierProductService;
    @Resource
    private IBizSupplierProductProcessService iBizSupplierProductProcessService;
    @Resource
    private IBizSupplierUserService iBizSupplierUserService;
    @Resource
    private IBizSupplierContactsService iBizSupplierContactsService;
    @Resource
    private IBizOutsourceBalanceAccountService iBizOutsourceBalanceAccountService;
    @Resource
    private ISysDeptService sysDeptService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private ISysConfigService configService;

    /**
     * 查询外协商列表
     */
    //@PreAuthorize("@ss.hasPermi('business:supplier:list')")
    @Log(title = "外协商单位查询", businessType = BusinessType.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(BizSupplier data) throws NoSuchFieldException, IllegalAccessException, JsonProcessingException {

        String config = configService.selectConfigByKey("switch_data_source");
        String tenantId = request.getHeader("tenantId");
        if ("true".equals(config) && tenantId != null && !"0".equals(tenantId)) {
            data.setTenantId(Long.parseLong(tenantId));
        }
        startPage();
        List<BizSupplier> list = iBizSupplierService.getList(data);
        return getDataTable(list);
    }

    @Log(title = "外协工段选择外协商单位", businessType = BusinessType.SELECT)
    @GetMapping("/listByDept")
    public TableDataInfo listByDept(SysDept dept) throws NoSuchFieldException, IllegalAccessException, JsonProcessingException {

        startPage();
        List<BizSupplier> list = iBizSupplierService.getListByDept(dept);
        return getDataTable(list);
    }
    @GetMapping(value = "/getOutsourceDept")
    @Log(title = "查询内部外协工段", businessType = BusinessType.SELECT)
    public AjaxResult getOutsourceDept(BizSupplier supplier) {
        return success(iBizSupplierService.getOutsourceDept(supplier));
    }

    /**
     * 获取外协商详细信息
     */
    //@PreAuthorize("@ss.hasPermi('business:supplier:query')")
    @Log(title = "外协商单位查询详细信息", businessType = BusinessType.SELECT)
    @GetMapping(value = "/getInfo/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(iBizSupplierService.getById(id));
    }

    /**
     * 新增外协商
     */
    //@PreAuthorize("@ss.hasPermi('business:supplier:add, business:supplier:edit')")
    @Log(title = "外协商单位保存", businessType = BusinessType.INSERT)
    @PostMapping(value = "/save")
    public AjaxResult save(@RequestBody BizSupplier bizSupplier) throws NoSuchFieldException, IllegalAccessException, JsonProcessingException {

        final String tenantId = request.getHeader("tenantId");
        bizSupplier.setTenantId(Long.valueOf(tenantId));

        QueryWrapper<BizSupplier> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tenant_id", Long.valueOf(tenantId));
        queryWrapper.eq("name", bizSupplier.getName());
        if(bizSupplier.getId() == null) {
            List<BizSupplier> supplierList = iBizSupplierService.query().eq("code", bizSupplier.getCode()).eq("tenant_id", tenantId).list();
            if (!supplierList.isEmpty()) {
                return AjaxResult.error("供应商编号不能重复");
            }
            supplierList = iBizSupplierService.query().eq("mnemonic_code", bizSupplier.getMnemonicCode()).eq("tenant_id", tenantId).list();
            if (!supplierList.isEmpty()) {
                return AjaxResult.error("助记码不能重复");
            }
        } else {
            BizSupplier prev = iBizSupplierService.getById(bizSupplier.getId());
            if (!prev.getIsInnerOutsource().equals(bizSupplier.getIsInnerOutsource()) && prev.getIsInnerOutsource().equals(1)) {
                // 判断是否所有发出单都收回
                if (!iBizSupplierService.checkAllReturn(bizSupplier)) {
                    return AjaxResult.error("有发出单未收回，不能修改");
                }
                // 修改工段关联的外协
                SysDept conditions = new SysDept();
                conditions.setSupplierId(bizSupplier.getId());
                List<SysDept> sysDepts = sysDeptService.selectDeptList(conditions);
                sysDepts.forEach(l -> {
                    l.setSupplierId(0L);
                    sysDeptService.updateDept(l);
                });
            }
        }
        long currentSupplierId = 0L;

        if (bizSupplier.getId() != null) {
            currentSupplierId = bizSupplier.getId();
        }
        queryWrapper.ne("id", currentSupplierId);
        List<BizSupplier> suppliers = iBizSupplierService.list(queryWrapper);
        if (!suppliers.isEmpty()) {
            return AjaxResult.warn("该外协商已存在");
        }
        boolean bool = iBizSupplierService.saveOrUpdate(bizSupplier);
        String msg = "";
        if (bool && currentSupplierId == 0L) {
            BizSupplierUser user = new BizSupplierUser();
            user.setTenantId(bizSupplier.getTenantId());
            user.setSupplierId(bizSupplier.getId());
            user.setSupplierCode(bizSupplier.getCode());
            user.setSupplierName(bizSupplier.getName());
            user.setUsername(bizSupplier.getCode());
            user.setPassword(SecurityUtils.encryptPassword("123456"));
            user.setIsAdmin("1");
            bool = iBizSupplierUserService.save(user);
            msg = !bool ? "外协商管理员保存失败！" : "";
        } else {
            msg = "外协商保存失败！";
        }
        return bool ? success(bizSupplier) : error(msg);
    }
    /**
     * 新增外协商联系人
     */
    //@PreAuthorize("@ss.hasPermi('business:supplier:add, business:supplier:edit')")
    @Log(title = "外协商联系人保存", businessType = BusinessType.INSERT)
    @PostMapping(value = "/saveSupplierContacts")
    public AjaxResult saveSupplierContacts(@RequestBody List<BizSupplierContacts> bizSupplierContacts) throws NoSuchFieldException, IllegalAccessException, JsonProcessingException {
        List<BizSupplierContacts> oldList = iBizSupplierContactsService.query().eq("supplier_id", bizSupplierContacts.get(0).getSupplierId()).list();
        saveOrUpdateBatch(iBizSupplierContactsService,bizSupplierContacts,oldList);
        return success();
    }
    /**
     * 查询外协商联系人
     */
    @Log(title = "外协商联系人查询", businessType = BusinessType.SELECT)
    @GetMapping(value = "/getSupplierContacts")
    public AjaxResult getSupplierContacts(BizSupplierContacts bizSupplierContacts) throws NoSuchFieldException, IllegalAccessException, JsonProcessingException {
        List<BizSupplierContacts> list = iBizSupplierContactsService.getList(bizSupplierContacts);
        return success(list);
    }

    /**
     * 删除外协商
     */
    //@PreAuthorize("@ss.hasPermi('business:supplier:remove')")
    @Log(title = "外协商单位删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/remove/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        return toAjax(iBizSupplierService.removeBatchByIds(ids));
    }

    /**
     * 获取供应商对应的产品信息
     * @param data 过滤条件
     * @return TableDataInfo
     */
    @Log(title = "外协商产品", businessType = BusinessType.SELECT)
    @GetMapping("/getSupplierProduct")
    public TableDataInfo getSupplierProduct(BizSupplierProduct data) {
        startPage();
        List<BizSupplierProduct> list = iBizSupplierProductService.getList(data);
        return getDataTable(list);
    }
    @Log(title = "外协商产品保存", businessType = BusinessType.INSERT)
    @PostMapping("/saveSupplierProduct")
    public AjaxResult saveSupplierProduct(@RequestBody List<BizSupplierProduct> data) {
        boolean bool = iBizSupplierProductService.saveOrUpdateBatch(data);
        return bool ? success("操作成功!") : error("操作失败!");
    }
    @Log(title = "外协商产品删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/removeSupplierProduct/{ids}")
    public AjaxResult removeSupplierProduct(@PathVariable List<Long> ids) {
        return toAjax(iBizSupplierProductService.removeBatchByIds(ids));
    }

    /**
     * 获取供应商对应的产品的工序信息
     * @param data 过滤条件
     * @return AjaxResult
     */
    @Log(title = "外协商产品工序查询", businessType = BusinessType.SELECT)
    @PostMapping("/getSupplierProductProcess")
    public AjaxResult getSupplierProductProcess(@RequestBody BizSupplierProductProcess data) {
        List<BizSupplierProductProcess> list = iBizSupplierProductProcessService.getList(data);
        return success(list);
    }
    @Log(title = "外协商产品工序保存", businessType = BusinessType.INSERT)
    @PostMapping("/saveSupplierProductProcess")
    public AjaxResult saveSupplierProductProcess(@RequestBody List<BizSupplierProductProcess> data) {
        boolean bool = iBizSupplierProductProcessService.saveOrUpdateBatch(data);
        //更新外协结算数据
        if(!data.isEmpty()) {
            Long productId = data.get(0).getProductId();
            Long supplierId = data.get(0).getSupplierId();
            List<Long> technologicalProcessIds = data.stream().map(BizSupplierProductProcess::getTechnologicalProcessId).collect(Collectors.toList());
            //对应产品的工序
            List<BizOutsourceBalanceAccount> list = iBizOutsourceBalanceAccountService.query()
                    .eq("product_id", productId).in("technological_process_id", technologicalProcessIds)
                    .eq("supplier_id", supplierId)
                    .eq("status",0)
                    .list();
            List<BizOutsourceBalanceAccount> totalList = new ArrayList<>();
            data.forEach(v->{
                List<BizOutsourceBalanceAccount> currentProcessList = list.stream().filter(v1 -> v1.getTechnologicalProcessId().equals(v.getTechnologicalProcessId()) && v1.getTechnologyVersion().equals(v.getTechnologyVersion())&& v1.getProcessStepNumber().equals(v.getProcessStepNumber())).collect(Collectors.toList());
                if(!currentProcessList.isEmpty()){
                    currentProcessList.forEach(v1->{
                        v1.setProcessPrice(v.getPrice());
                    });
                    totalList.addAll(currentProcessList);
                }
            });
            iBizOutsourceBalanceAccountService.updateBatchById(totalList);
        }
        return bool ? success("操作成功!") : error("操作失败!");
    }
    @Log(title = "外协商产品工序删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/removeSupplierProductProcess/{ids}")
    public AjaxResult removeSupplierProductProcess(@PathVariable List<Long> ids) {
        BizSupplierProductProcess supplierProductProcess = iBizSupplierProductProcessService.query().in("id", ids).one();
        Long productId = supplierProductProcess.getProductId();
        //对应产品的工序
        List<BizOutsourceBalanceAccount> list = iBizOutsourceBalanceAccountService.query()
                .eq("product_id", productId).eq("technological_process_id", supplierProductProcess.getTechnologicalProcessId())
                .eq("supplier_id",supplierProductProcess.getSupplierId())
                .eq("status",0)
                .list();
        List<BizOutsourceBalanceAccount> totalList = new ArrayList<>();
        List<BizOutsourceBalanceAccount> currentProcessList = list.stream().filter(v1 -> v1.getTechnologicalProcessId().equals(supplierProductProcess.getTechnologicalProcessId()) && v1.getTechnologyVersion().equals(supplierProductProcess.getTechnologyVersion())&& v1.getProcessStepNumber().equals(supplierProductProcess.getProcessStepNumber())).collect(Collectors.toList());
        if(!currentProcessList.isEmpty()){
            currentProcessList.forEach(v1->{
                v1.setProcessPrice(BigDecimal.valueOf(0));
            });
            totalList.addAll(currentProcessList);
        }
        iBizOutsourceBalanceAccountService.updateBatchById(totalList);
        return toAjax(iBizSupplierProductProcessService.removeBatchByIds(ids));
    }

    /**
     * 获取供应商的管理员信息
     * @param supplierId 外协商id
     * @return BizSupplierUser
     */
    @Log(title = "外协商管理员查询", businessType = BusinessType.DELETE)
    @GetMapping("/getAdminInfo/{supplierId}")
    public AjaxResult getAdminInfo(@PathVariable Long supplierId) {
        return success(iBizSupplierUserService.getAdminInfo(supplierId));
    }

    /**
     * 保存供应商的管理员信息
     * @param user 管理员信息
     * @return AjaxResult
     */
    @Log(title = "外协商管理员保存", businessType = BusinessType.DELETE)
    @PostMapping("/saveAdmin")
    public AjaxResult saveAdmin(@RequestBody BizSupplierUser user) {
        if (user.getId() == null) {
            // 添加管理员时，设置默认密码：123456
            user.setPassword(SecurityUtils.encryptPassword("123456"));
        }
        boolean bool = iBizSupplierUserService.saveOrUpdate(user);
        return bool ? success("操作成功!") : error("操作失败!");
    }

    /**
     * 初始化供应商的管理员密码
     * @param user 管理员信息
     * @return AjaxResult
     */
    @Log(title = "外协商管理员密码初始化", businessType = BusinessType.DELETE)
    @PostMapping("/initAdminPsw")
    public AjaxResult initAdminPsw(@RequestBody BizSupplierUser user) {
        user.setPassword(SecurityUtils.encryptPassword("123456"));
        boolean bool = iBizSupplierUserService.saveOrUpdate(user);
        return bool ? success("操作成功!") : error("操作失败!");
    }
}
