package org.linlinjava.jz.admin.web;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.linlinjava.jz.admin.annotation.RequiresPermissionsDesc;
import org.linlinjava.jz.admin.service.AdminCustomerOrderService;
import org.linlinjava.jz.core.util.DateTimeUtil;
import org.linlinjava.jz.core.util.ResponseUtil;
import org.linlinjava.jz.db.domain.*;
import org.linlinjava.jz.db.dto.hm.HmEmployClockUpdateDto;
import org.linlinjava.jz.db.dto.hm.HmSetTaskItemDTO;
import org.linlinjava.jz.db.service.*;
import org.linlinjava.jz.db.service.hm.*;
import org.linlinjava.jz.db.util.hm.HmCommentEnum;
import org.linlinjava.jz.service.HmEmployClockService;
import org.linlinjava.jz.service.HmServantIncomeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.text.ParseException;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author fuxubing
 */
@Api(value = "Admin-CustomerOrder-Controller", description = "保姆订单中心")
@RestController
@RequestMapping("/admin/customerOrder")
@Validated
public class AdminCustomerOrderController {
    private final Log logger = LogFactory.getLog(AdminCustomerController.class);

    @Autowired
    private AdminCustomerOrderService adminCustomerOrderService;
    @Autowired
    private CustomerClientService customerClientService;
    @Autowired
    private JzCustomerFnService fnService;
    @Autowired
    private ContractMasterService contractMasterService;
    @Autowired
    private ContractSubTemplateService contractSubTemplateService;
    @Autowired
    private HmEmployRelationService hmEmployRelationService;
    @Autowired
    private HmAppUserService hmAppUserService;
    @Autowired
    private HmEmployTaskSetService hmEmployTaskSetService;
    @Autowired
    private HmEmployTaskService hmEmployTaskService;
    @Autowired
    private HmCommentService hmCommentService;
    @Autowired
    private CustomerClueService customerClueService;
    @Resource
    private HmEmployClockService hmEmployClockService;
    @Resource
    private HmServantIncomeService hmServantIncomeService;


    @RequiresPermissions("admin:customerOrder:list")
    @RequiresPermissionsDesc(menu = {"订单中心", "保姆订单"}, button = "查询")
    @ApiOperation("订单中心-保姆订单列表")
    @GetMapping("/list")
    public Object list(@RequestParam(required = false) String customerName,
                       @RequestParam(required = false) String customerTel,
                       @NotNull @RequestParam Long userId,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "20") Integer limit) {
        List<Map<String, Object>> list = adminCustomerOrderService.list(customerName, customerTel,userId, page, limit);
        return ResponseUtil.okList(list);
    }

    @RequiresPermissions("admin:customerOrder:detail")
    @RequiresPermissionsDesc(menu = {"订单中心", "保姆订单详情"}, button = "详情")
    @ApiOperation("订单中心-保姆订单详情")
    @GetMapping("/detail")
    public Object detail(@NotNull @RequestParam Long id) throws ParseException {
        CustomerOrder customerOrder = adminCustomerOrderService.selectById(id);
        if (null == customerOrder) {
            return ResponseUtil.badArgumentValue();
        }
        CustomerClue customerClue = customerClueService.selectByClueNo(customerOrder.getClueNo());
        //客户
        CustomerClient customerClient = customerClientService.findUserByMobile(customerOrder.getCustomerTel());
        //亲情号
//        List<CustomerFn> fns = fnService.queryByCustomerId(customerClient.getId().intValue());
        //订单合同信息
        Map<String, Object> orderInfoMap = contractMasterService.selectByOrderNo(customerOrder.getOrderNo());
        //服务信息
        ContractSubTemplate contractSubTemplate = contractSubTemplateService.selectByOrderNo(customerOrder.getOrderNo());
        if (null == contractSubTemplate) {
            return ResponseUtil.fail();
        }
        //雇主关系
        HmEmployRelation employRelation = hmEmployRelationService.queryByOrderNo(customerOrder.getOrderNo());
        if (null == employRelation) {
            return ResponseUtil.fail();
        }

        HmAppUser userCustomer = hmAppUserService.queryById(employRelation.getUserEmployerId());
        HmAppUser userServant = hmAppUserService.queryById(employRelation.getUserServantId());
        HmAppUser userButler = hmAppUserService.queryById(employRelation.getUserButlerId());

//            contractSubTemplate.setOffDay(employRelation.getRestDay());
        contractSubTemplate.setServiceStartTime(employRelation.getFirstServiceTime());
        contractSubTemplate.setIsNeedClock(employRelation.getIsNeedClock());
        contractSubTemplate.setTel(userCustomer.getPhone());


        Map<String, Object> data = new HashMap<>(16);
        data.put("user", customerClient);
//        data.put("fns", fns);
        data.put("orderInfo", orderInfoMap);
        data.put("serviceInfo", contractSubTemplate);
        data.put("userCustomer", userCustomer);
        data.put("userServant", userServant);
        data.put("employRelation", employRelation);
        data.put("customerOrder", customerOrder);
        data.put("customerClue", customerClue);
        data.put("userButler", userButler);
        //薪资计算
        LocalDate firstDayOfMonth = DateTimeUtil.firstDayOfMonth(LocalDate.now());
        LocalDate lastDayOfMonth = DateTimeUtil.lastDayOfMonth(LocalDate.now());

        BigDecimal totalIncome = hmServantIncomeService.getTotalIncome(employRelation.getId(), contractSubTemplate, firstDayOfMonth, lastDayOfMonth);
        data.put("totalIncome", totalIncome);
        return ResponseUtil.ok(data);
    }

    @RequiresPermissionsDesc(menu = {"订单中心", "保姆任务清单"}, button = "查询")
    @ApiOperation("订单中心-保姆任务清单")
    @GetMapping("/taskList")
    public Object taskList(@NotNull @RequestParam Long id) {
        CustomerOrder customerOrder = adminCustomerOrderService.selectById(id);
        if (null == customerOrder) {
            return ResponseUtil.badArgumentValue();
        }
        Map<String, Object> map = hmEmployTaskSetService.queryGroupByTaskType(customerOrder.getOrderNo());
        return ResponseUtil.ok(map);
    }

    @RequiresPermissionsDesc(menu = {"订单中心", "任务库"}, button = "查询")
    @ApiOperation("订单中心-编辑任务展示")
    @GetMapping("/taskItemList")
    public Object taskItemList(@NotNull @RequestParam Long id, @NotNull @RequestParam int taskType) {
        CustomerOrder customerOrder = adminCustomerOrderService.selectById(id);
        if (null == customerOrder) {
            return ResponseUtil.badArgumentValue();
        }
        List<Map<String, Object>> mapList = hmEmployTaskSetService.selectChooseTaskItem(customerOrder.getOrderNo(), taskType);
        return ResponseUtil.ok(mapList);
    }

    @RequiresPermissionsDesc(menu = {"订单中心", "任务设置"}, button = "保存")
    @ApiOperation("订单中心-任务设置")
    @PostMapping("/setTask")
    public Object setTask(@Valid @RequestBody HmSetTaskItemDTO hmSetTaskItemDTO) {
        if (hmSetTaskItemDTO.getId() == null) {
            return ResponseUtil.fail(401, "订单id不能为空");
        }

        CustomerOrder customerOrder = adminCustomerOrderService.selectById(hmSetTaskItemDTO.getId());
        if (null == customerOrder) {
            return ResponseUtil.badArgumentValue();
        }
        hmEmployTaskSetService.setTask(customerOrder.getOrderNo(), hmSetTaskItemDTO);
        return ResponseUtil.ok();
    }


    @RequiresPermissionsDesc(menu = {"订单中心", "服务信息补充编辑"}, button = "保存")
    @ApiOperation("订单中心-服务信息补充编辑")
    @GetMapping("/editServiceInfo")
    public Object editServiceInfo(@NotNull @RequestParam Long orderId, @NotNull @RequestParam Integer isNeedClock,
                                  @NotNull @RequestParam String mobile, Long taskChildId) {
        CustomerOrder customerOrder = adminCustomerOrderService.selectById(orderId);
        if (null == customerOrder) {
            return ResponseUtil.badArgumentValue();
        }
        // @NotNull @RequestParam String restDay,
        hmEmployRelationService.update(customerOrder.getOrderNo(), isNeedClock, mobile, taskChildId);

        return ResponseUtil.ok();
    }

    @RequiresPermissionsDesc(menu = {"订单中心", "服务信息-修改休息日"}, button = "保存")
    @ApiOperation("订单中心-服务信息-修改休息日")
    @GetMapping("/editServantRestDay")
    public Object editServantRestDay(@NotNull @RequestParam Long employRelationId, @NotNull @RequestParam String restDay) {
        hmEmployRelationService.updateRestDay(employRelationId, restDay);

        return ResponseUtil.ok();
    }

    @RequiresPermissionsDesc(menu = {"订单中心", "保姆服务记录"}, button = "查询")
    @ApiOperation("订单中心-保姆服务记录")
    @GetMapping("/taskClockList")
    public Object taskClockList(@NotNull @RequestParam Long id, @RequestParam(defaultValue = "1") Integer page,
                                @RequestParam(defaultValue = "10") Integer limit, Long clockId) {
        CustomerOrder customerOrder = adminCustomerOrderService.selectById(id);
        if (null == customerOrder) {
            return ResponseUtil.badArgumentValue();
        }
        List<HmEmployClock> hmEmployClocks = adminCustomerOrderService.queryTaskClockList(customerOrder.getOrderNo(), clockId, page, limit);
        return ResponseUtil.okList(hmEmployClocks);
    }

    @RequiresPermissionsDesc(menu = {"订单中心", "保姆服务记录详情"}, button = "查询")
    @ApiOperation("订单中心-保姆服务记录")
    @GetMapping("/taskClockDetail")
    public Object taskClockDetail(@NotNull @RequestParam Long id) {
        HmEmployClock hmEmployClock = adminCustomerOrderService.queryById(id);
        if (null == hmEmployClock) {
            return ResponseUtil.badArgumentValue();
        }
        //任务打卡记录
        List<Map<String, Object>> dayTask = hmEmployTaskService.queryByClockId(id, 1, null);
        List<Map<String, Object>> weekTask = hmEmployTaskService.queryByClockId(id, 2, null);
        List<Map<String, Object>> monthTask = hmEmployTaskService.queryByClockId(id, 3, null);
        //评价
        HmComment hmComment = hmCommentService.queryByRIdAndType(id, HmCommentEnum.comment_num_3.getType());

        Map<String, Object> map = new HashMap<>(16);

        map.put("hmEmployClock", hmEmployClock);
        map.put("dayTask", dayTask);
        map.put("weekTask", weekTask);
        map.put("monthTask", monthTask);
        map.put("hmComment", hmComment);

        return ResponseUtil.ok(map);
    }

    @ApiOperation(value = "管家-保姆服务记录编辑-查看每日打卡任务详情", notes = "管家-保姆服务记录编辑-查看每日打卡任务详情")
    @GetMapping("/getServantClockInfo")
    public Object getServantClockInfo(Long employClockId) {
        HmEmployClock servantClockInfo = hmEmployClockService.getServantClockInfo(employClockId);
        return ResponseUtil.ok(servantClockInfo);
    }

    @ApiOperation(value = "管家-保姆服务记录每日打卡编辑-保存", notes = "管家-保姆服务记录每日打卡编辑-保存")
    @PostMapping("/updateServantClockInfo")
    public Object updateServantClockInfo(@RequestBody HmEmployClockUpdateDto emClock) {
        hmEmployClockService.updateEmployClockInof(emClock);
        return ResponseUtil.ok();
    }

    @RequiresPermissionsDesc(menu = {"订单中心", "服务信息-查看历史薪资"}, button = "查询")
    @ApiOperation("订单中心-服务信息-查看历史薪资")
    @GetMapping("/getHistoryIncome")
    public Object getHistoryIncome(@NotNull @RequestParam Long id) throws Exception {
        CustomerOrder customerOrder = adminCustomerOrderService.selectById(id);
        if (null == customerOrder) {
            return ResponseUtil.badArgumentValue();
        }


        HmEmployRelation hmEmployRelation = hmEmployRelationService.queryByOrderNo(customerOrder.getOrderNo());
        if (null == hmEmployRelation) {
            return ResponseUtil.badArgumentValue();
        }

        //服务信息
        ContractSubTemplate contractSubTemplate = contractSubTemplateService.selectByOrderNo(hmEmployRelation.getOrderNo());
        if (null == contractSubTemplate) {
            return ResponseUtil.badArgumentValue();
        }

        List<Map<String, Object>> historyIncome = hmServantIncomeService.getHistoryIncome(hmEmployRelation.getId(), contractSubTemplate);
        return ResponseUtil.ok(historyIncome);
    }

}
