package cn.com.ctop.reimburse.mondule.controller;

import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.ExportExcelUtils;
import cn.com.ctop.common.module.utils.HttpUtils;
import cn.com.ctop.reimburse.mondule.entity.ReimburseApply;
import cn.com.ctop.reimburse.mondule.entity.ReimburseDict;
import cn.com.ctop.reimburse.mondule.entity.ReimburseProject;
import cn.com.ctop.reimburse.mondule.service.IReimburseApplyService;
import cn.com.ctop.reimburse.mondule.service.IReimburseDictService;
import cn.com.ctop.reimburse.mondule.service.IReimburseProjectService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.system.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 报销申请提交表
 */
@Slf4j
@Api(tags = "报销申请提交表")
@RestController
@RequestMapping("/reimburse/apply")
public class ReimburseApplyController {
    @Autowired
    private IReimburseApplyService reimburseApplyService;

    @Autowired
    private IReimburseDictService reimburseDictService;

    @Autowired
    private IReimburseProjectService projectService;
    @Autowired
    private ISysRoleService sysRoleService;

    /**
     * 分页列表查询
     */
    @GetMapping(value = "/list")
    public Result<Object> queryPageList(ReimburseApply reimburseApply,
                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize
    ) {
        try {
            //查询用户角色
            String roleCode = sysRoleService.getRoleCodeByUserId(reimburseApply.getUserId());
            if ("financialReview".equals(roleCode)) {
                //财务查询
                reimburseApply.setFinancialReview(1);
            } else if ("admin".equals(roleCode) && "e9ca23d68d884d4ebb19d07889727dae".equals(reimburseApply.getUserId())) {
                //管理员
                reimburseApply.setFinancialReview(2);
            }
            return reimburseApplyService.queryPageList(reimburseApply, pageNo, pageSize);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败！");
        }
    }

    @GetMapping(value = "/excel")
    public void queryExcel(HttpServletResponse response, ReimburseApply reimburseApply) {
        //查询用户角色
        String roleCode = sysRoleService.getRoleCodeByUserId(reimburseApply.getUserId());
        if ("financialReview".equals(roleCode)) {
            //财务查询
            reimburseApply.setFinancialReview(1);
        } else if ("admin".equals(roleCode) && "e9ca23d68d884d4ebb19d07889727dae".equals(reimburseApply.getUserId())) {
            //管理员
            reimburseApply.setFinancialReview(2);
        }
        List<JSONObject> list = reimburseApplyService.queryList(reimburseApply);
        if (!Check.isNull(list)) {
            List<ReimburseDict> dictList = reimburseDictService.list();
            Map<String, String> map = new HashMap<>();
            for (ReimburseDict dict : dictList) {
                map.put(dict.getDcode(), dict.getDname());
            }
            try {
                List<List<Object>> excelList = new ArrayList<>();
                if (!list.isEmpty()) {
                    for (JSONObject info : list) {
                        List<Object> temp = new ArrayList<>();
                        temp.add(info.getString("id"));
                        temp.add(info.getString("userName"));
                        temp.add(info.getString("departName"));
                        temp.add(info.getString("companyName"));
                        temp.add(info.getString("media"));
                        temp.add(info.getString("type"));
                        temp.add(map.get(info.getString("project")));
                        temp.add(info.getString("amount"));
                        temp.add(info.getString("expenseDate"));
                        temp.add(info.getString("statDate"));
                        temp.add(info.getString("remarks"));
                        temp.add(info.getString("status"));
                        excelList.add(temp);
                    }
                }
                OutputStream os = response.getOutputStream();
                ExportExcelUtils eeu = new ExportExcelUtils();
                XSSFWorkbook workbook = new XSSFWorkbook();

                String[] titles = {"编号", "申请人", "部门", "主体", "媒体线", "报销类别", "报销项目", "报销金额", "费用产生日期", "申请时间", "备注", "状态"};
                eeu.exportExcelForAttendance(workbook, 0, "审核信息", titles, excelList);
                HttpUtils.setResponseHeader(response, "clockIn.xlsx");
                workbook.write(os);
                os.flush();
                os.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
    }

    /**
     * 添加
     */
    @PostMapping(value = "/add")
    public Result<Object> add(@RequestBody JSONObject data) {
        try {
            return reimburseApplyService.add(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("添加失败！");
        }
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryProcess")
    public Result<Object> queryProcess(@RequestParam(name = "id", required = true) String id) {
        ReimburseApply reimburseApply = reimburseApplyService.getById(id);
        if (reimburseApply == null) {
            return Result.error("未找到对应实体");
        } else {
            List<JSONObject> list = reimburseApplyService.queryProcess(reimburseApply.getId());
            return Result.ok(list);
        }
    }


    /**
     * 编辑
     */
    @PostMapping(value = "/edit")
    public Result<Object> edit(@RequestBody JSONObject data) {
        try {
            return reimburseApplyService.edit(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("修改失败！");
        }
    }

    /**
     * 提交审核
     */
    @GetMapping(value = "/submitReview")
    public Result<Object> submitReview(String id) {
        try {
            return reimburseApplyService.submitReview(id);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("操作失败！");
        }
    }


    /**
     * 通过id删除
     */
    @GetMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id") String id) {
        try {
            reimburseApplyService.removeById(id);
        } catch (Exception e) {
            log.error("删除失败", e.getMessage());
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @ApiOperation(value = "报销申请提交表-批量删除", notes = "报销申请提交表-批量删除")
    @GetMapping(value = "/deleteBatch")
    public Result<ReimburseApply> deleteBatch(@RequestParam(name = "ids") String ids) {
        Result<ReimburseApply> result = new Result<>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.reimburseApplyService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "报销申请提交表-通过id查询", notes = "报销申请提交表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<ReimburseApply> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<ReimburseApply> result = new Result<>();
        ReimburseApply reimburseApply = reimburseApplyService.getById(id);
        if (reimburseApply == null) {
            result.error500("未找到对应实体");
        } else {
            QueryWrapper<ReimburseProject> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("apply_id", reimburseApply.getId());
            List<ReimburseProject> list = projectService.list(queryWrapper);
            List<Long> ids = new ArrayList<>();
            for (ReimburseProject project : list) {
                ids.add(project.getId());
            }
            reimburseApply.setIds(JSONObject.toJSONString(ids));
            result.setResult(reimburseApply);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 列表查询
     */
    @GetMapping(value = "/getCompanyList")
    public Result<Object> getCompanyList() {
        return Result.ok(reimburseApplyService.getCompanyList());
    }

}
