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

import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.ezhizao.project.business.company.domain.BizCompany;
import cn.ezhizao.project.business.company.mapper.BizCompanyMapper;
import cn.ezhizao.project.business.company.service.IBizCompanyService;
import cn.ezhizao.project.business.recycleBin.domain.BizRecycleBin;
import cn.ezhizao.project.business.recycleBin.service.IBizRecycleBinService;
import lombok.Getter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
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.common.utils.poi.ExcelUtil;
import cn.ezhizao.framework.web.page.TableDataInfo;

/**
 * 回收站Controller
 *
 * @author ruoyi
 * @date 2023-11-02
 */
@RestController
@RequestMapping("/business/bin")
public class BizRecycleBinController extends BaseController {
    @Resource
    private IBizRecycleBinService bizRecycleBinService;

    @Resource
    private IBizCompanyService bizCompanyService;

    @Resource
    private BizCompanyMapper bizCompanyMapper;

    //客户关联的数据表
    @Getter
    private String[] tabs = {"biz_archive_borrow", "biz_archive_input", "biz_archive_dictionary", "biz_archive_input_detail"
            , "biz_archive_input_detail_process"
            , "biz_archive_output", "biz_archive_receive_ticket", "biz_company_contactor", "biz_company_follow_detail", "biz_company_original_name",
            "biz_entrust_detail", "biz_entrust_permission", "biz_entrust", "biz_financial_account_adjustment", "biz_financial_individual_income_tax",
            "biz_financial_individual_income_tax_detail", "biz_financial_keep_account", "biz_financial_keep_account_detail", "biz_financial_receive_ticket",
            "biz_financial_receive_ticket_detail", "biz_financial_receive_ticket_feedback", "biz_financial_receive_ticket_feedback",
            "biz_financial_report_tax_detail", "biz_financial_salary_detail_employee", "biz_financial_urgent", "biz_housing_fund_confirm",
            "biz_housing_fund_confirm_detail", "biz_housing_fund_confirm_detail_employee", "biz_housing_fund_declare", "biz_housing_fund_declare_detail",
            "biz_social_security_confirm", "biz_social_security_confirm_detail", "biz_social_security_confirm_detail_employee",
            "biz_social_security_declare", "biz_social_security_declare_detail"};


    /**
     * 查询回收站列表
     */
    @PreAuthorize("@ss.hasPermi('business:bin:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizRecycleBin bizRecycleBin) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(bizRecycleBin);
        startPage();
        startOrderBy();
        List<BizRecycleBin> list = bizRecycleBinService.getList(bizRecycleBin);
        return getDataTable(list);
    }

    /**
     * 导出回收站列表
     */
    @PreAuthorize("@ss.hasPermi('business:bin:export')")
    @Log(title = "回收站", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizRecycleBin bizRecycleBin) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(bizRecycleBin);
        List<BizRecycleBin> list = bizRecycleBinService.getList(bizRecycleBin);
        ExcelUtil<BizRecycleBin> util = new ExcelUtil<BizRecycleBin>(BizRecycleBin.class);
        util.exportExcel(response, list, "回收站数据");
    }

    /**
     * 获取回收站详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:bin:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(bizRecycleBinService.getById(id));
    }

    /**
     * 新增回收站
     */
    @PreAuthorize("@ss.hasPermi('business:company:remove')")
    @Log(title = "回收站", businessType = BusinessType.INSERT)
    @PostMapping("/{ids}")
    public AjaxResult add(@PathVariable List<Long> ids) throws NoSuchFieldException, IllegalAccessException {
        BizCompany com = new BizCompany();
        List<BizRecycleBin> recycleBins = new ArrayList<>();
        //遍历id查询客户数据并在回收站中插入
        for (Long id : ids) {
            BizRecycleBin bin = new BizRecycleBin();
            com = bizCompanyMapper.getById(id);
            bin.setFromId(0L);
            bin.setSourceValue(com.getName());
            bin.setSourceTableName("biz_company");
            bin.setSourceId(com.getId());
            setTenantId(bin);
            bizRecycleBinService.save(bin);
            //软删除客户关联子表数据
            bizRecycleBinService.deleteData(id, tabs);
            List<Map<String, Object>> tabList = Arrays.stream(tabs).map(v -> {
                Map<String, Object> map = new HashMap<>();
                map.put("tab", v);
                map.put("id", id);
                return map;
            }).collect(Collectors.toList());
            List<BizRecycleBin> children = bizRecycleBinService.getChildIdsByParentId(tabList);
            Long tenantId = getTenantId();
            BizCompany finalCom = com;
            children.forEach(child -> {
                child.setFromId(bin.getId());
                child.setSourceValue(finalCom.getName());
                child.setTenantId(tenantId);
                recycleBins.add(child);
            });
        }
        //查询客户关联子表数据在回收站中插入
        bizRecycleBinService.saveBatch(recycleBins);
        //删除客户表数据
        return toAjax(bizCompanyService.removeBatchByIds(ids));
    }

    @PreAuthorize("@ss.hasPermi('business:bin:add')")
    @Log(title = "回收站", businessType = BusinessType.INSERT)
    @PostMapping("/old/{ids}")
    public void addOld(@PathVariable List<Long> ids) throws NoSuchFieldException, IllegalAccessException
    {
        BizCompany com=new BizCompany();
        //遍历id查询客户数据并在回收站中插入
        for (Long id:ids) {
            BizRecycleBin bin =new BizRecycleBin();
            com=bizCompanyMapper.getById(id);
            bin.setFromId(0L);
            bin.setSourceValue(com.getName());
            bin.setSourceTableName("biz_company");
            bin.setSourceId(com.getId());
            setTenantId(bin);
            bizRecycleBinService.save(bin);
            //软删除客户关联子表数据
            bizRecycleBinService.deleteData(id,tabs);

            //查询客户关联子表数据在回收站中插入
            for (String tab:tabs) {
                //查询客户关联子表id
                Long childId=bizRecycleBinService.getChildById(id,tab);
                //如果返回id不为空则将数据插入回收站
                if (childId!=null&& !childId.equals("")){
                    BizRecycleBin rbiz =new BizRecycleBin();
                    rbiz.setFromId(bin.getId());
                    rbiz.setSourceValue(com.getName());
                    rbiz.setSourceTableName(tab);
                    rbiz.setSourceId(childId);
                    setTenantId(rbiz);
                    bizRecycleBinService.save(rbiz);
                }
            }
        }
    }


    /**
     * 修改回收站
     */
    @PreAuthorize("@ss.hasPermi('business:bin:edit')")
    @Log(title = "回收站", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizRecycleBin bizRecycleBin) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(bizRecycleBin);
        return toAjax(bizRecycleBinService.updateById(bizRecycleBin));
    }

    /**
     * 删除回收站
     */
    @PreAuthorize("@ss.hasPermi('business:bin:remove')")
    @Log(title = "回收站", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        bizRecycleBinService.remove(ids);
        return toAjax(bizRecycleBinService.removeBatchByIds(ids));
    }

    /**
     * 还原回收站
     */
    @PreAuthorize("@ss.hasPermi('business:bin:restore')")
    @PostMapping("/restore/{ids}")
    public AjaxResult restore(@PathVariable List<Long> ids) {
        return toAjax(bizRecycleBinService.restore(ids));
    }
}
