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

import cn.ezhizao.common.utils.SecurityUtils;
import cn.ezhizao.common.utils.StringUtils;
import cn.ezhizao.common.utils.poi.ExcelUtil;
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.entrust.domain.BizEntrust;
import cn.ezhizao.project.business.entrust.service.IBizEntrustService;
import cn.ezhizao.project.business.workOrder.domain.BizWorkOrder;
import cn.ezhizao.project.business.workOrder.domain.BizWorkOrderRecord;
import cn.ezhizao.project.business.workOrder.service.IBizWorkOrderRecordService;
import cn.ezhizao.project.business.workOrder.service.IBizWorkOrderService;
import cn.ezhizao.project.system.domain.SysDictData;
import cn.ezhizao.project.system.domain.SysUser;
import cn.ezhizao.project.system.mapper.SysUserMapper;
import cn.ezhizao.project.system.service.ISysDictDataService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * @author 周晓
 */
@RestController
@Api(tags = "单次任务数据接口")
@RequestMapping(value = "/business/onceWorkOrder")
public class OnceWorkOrderProductionController extends BaseController {
    @Resource
    IBizWorkOrderService workOrderService;
    @Resource
    IBizWorkOrderRecordService workOrderRecordService;
    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private ISysDictDataService sysDictDataService;

    @Resource
    private IBizEntrustService entrustService;

    @ApiOperation(value = "带条件List 分页查询", notes = "带条件List 分页查询")
    @GetMapping("/list")
    @PreAuthorize("@ss.hasPermi('business:production:onceWork:list')")
    @ResponseBody
    public TableDataInfo getList(BizWorkOrder conditions) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(conditions);
        startPage();
        startOrderBy();
        List<BizWorkOrder> list = workOrderService.getList(conditions);
        list.forEach(v -> {
            Integer style = v.getAddressStyle();
            if (style == null) {
                return;
            }
            if (v.getTaskTypeId() == 5L && style == 1 && StringUtils.isNotEmpty(v.getInputProvince())) {
                //自有地址
                v.setExplain("自有地址:" + v.getInputProvince() + v.getInputCity() + v.getInputDistrict());
            } else if (v.getTaskTypeId() == 5L && style == 2 && v.getFictionAddressId() != null) {
                //虚拟地址
                SysDictData sysDictData = sysDictDataService.selectDictDataById(v.getFictionAddressId());
                if (sysDictData == null) {
                    return;
                }
                v.setExplain("虚拟地址:" + sysDictData.getDictLabel());
            } else {
                if (StringUtils.isEmpty(v.getInputProvince())) {
                    return;
                }
                v.setExplain("办理地区:" + v.getInputProvince() + v.getInputCity() + v.getInputDistrict());
            }

        });
//        .stream().filter(s -> s.getCompanyName().contains(companyName)).collect(Collectors.toList())
        return getDataTable(list);
    }

    /**
     * 导出划款列表
     */
    @PreAuthorize("@ss.hasPermi('business:production:onceexport')")
    @Log(title = "单次任务", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizWorkOrder conditions) throws NoSuchFieldException, IllegalAccessException {
        setTenantId(conditions);
        startOrderBy();
        List<BizWorkOrder> list = workOrderService.getList(conditions);
        for (BizWorkOrder l : list) {
            l.setProjectType((l.getNoContract() == 1 ? l.getRemark() : "") + l.getTaskTypeName() + (l.getTaskTypeDetailName() != null ? "-" + l.getTaskTypeDetailName() : ""));
            l.setOrderType(l.getType() == 1 ? "循环工单" : "代办工单");

            List<BizWorkOrderRecord> records = workOrderRecordService.query()
                    .eq("work_order_id", l.getId()).eq("from_id", 0).list();
            if (records.size() > 0) {
                Long workOrderId = records.get(0).getWorkOrderId();
                BizEntrust one = entrustService.getOne(new LambdaQueryWrapper<BizEntrust>().eq(BizEntrust::getWorkOrderId, workOrderId));
                if (records.get(0).getRecorderId()!= null){
//                    SysUser sysUser = sysUserMapper.selectUserById(records.get(0).getRecorderId());
                    SysUser sysUser = sysUserMapper.selectUserById(l.getServiceId());
                    l.setServiceName(sysUser == null ? "" : sysUser.getNickName());
//                    l.setRecorderName(sysUser == null ? "" : sysUser.getNickName());
                    l.setRecorderName(l.getRecord().getRecorderName() == null ? "" : l.getRecord().getRecorderName());
                }
                if (records.get(0).getHandlerId()!= null){
                    SysUser sysUser2 = sysUserMapper.selectUserById(records.get(0).getHandlerId());
                    l.setHandlerName(sysUser2 == null ? "" : sysUser2.getNickName());
                }
                l.setHandlerTime(records.get(0).getHandlerTime());
                l.setEntrustTime(one.getCreateTime());
                l.setFinishTime(records.get(0).getUpdateTime());
            } else {
                l.setServiceName("");
                l.setHandlerName("");
            }
            //设置状态
            switch (l.getRecord() == null ? 0 : l.getRecord().getStatus()) {
                case 0:
                    l.setStatusType("未开始");
                    break;

                case 3:
                    l.setStatusType("已完成");
                    break;
                default:
                    break;
            }

        }
        ExcelUtil<BizWorkOrder> util = new ExcelUtil<BizWorkOrder>(BizWorkOrder.class);
        util.exportExcel(response, list, "单次任务数据");
    }

    @PreAuthorize("@ss.hasPermi('business:production:onceWork:query')")
    @PostMapping("/getDetail")
    public AjaxResult getDetail(@RequestBody BizWorkOrderRecord detail) {
        List<BizWorkOrderRecord> workOrderRecords = workOrderRecordService.getList(detail);
        if (workOrderRecords.isEmpty()) {
            return success(detail);
        }
        return success(workOrderRecords.get(0));
    }

    @PreAuthorize("@ss.hasPermi('business:production:onceWork:finished')")
    @PostMapping("/finished")
    public AjaxResult finished(@RequestBody BizWorkOrderRecord detail) {
        // 获取是否已完成 已完成不能再次完成
        BizWorkOrderRecord conditions = new BizWorkOrderRecord();
        conditions.setWorkOrderId(detail.getWorkOrderId());
        conditions.setYear(detail.getYear());
        conditions.setMonth(detail.getMonth());
        if (workOrderRecordService.getList(conditions).stream().anyMatch(v -> !v.getId().equals(detail.getId()))) {
            return error("该工单已完成,请刷新列表。");
        }
        if (detail.getId() == null) {
            detail.setStatus(3);
            detail.setRecorderId(SecurityUtils.getUserId());
            return toAjax(workOrderRecordService.save(detail));
        } else {
            detail.setStatus(3);
            detail.setRecorderId(SecurityUtils.getUserId());
            detail.setFinishTime(new Date());
            return toAjax(workOrderRecordService.updateById(detail));
        }
    }


    @PostMapping("/receive")
    @Log(title = "办理", businessType = BusinessType.UPDATE)
    public AjaxResult receive(@RequestBody BizWorkOrderRecord record) {
        // 获取是否已完成 已完成不能再次完成
        if (record.getId() != null) {
            record.setStatus( workOrderRecordService.getById(record.getId()).getStatus() == 0 ? 1: 0);
        } else {
            record.setStatus(1);
        }
        if (record.getStatus() ==1){
            record.setHandlerId(SecurityUtils.getUserId());
            record.setHandlerTime(new Date());
        }else {
            Long handlerId = workOrderRecordService.getById(record.getId()).getHandlerId();
            if (!handlerId.equals(SecurityUtils.getUserId()) ){
                return error("只能由当前办理人取消");
            }
            record.setHandlerId(null);
            record.setHandlerTime(null);
        }
        return toAjax(workOrderRecordService.saveOrUpdate(record));
    }
}
