package com.pm.web.controller.repairOrder;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Date;
import java.text.SimpleDateFormat;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
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.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 com.pm.common.annotation.Log;
import com.pm.common.core.controller.BaseController;
import com.pm.common.core.domain.AjaxResult;
import com.pm.common.enums.BusinessType;
import com.pm.common.config.PageData;
import com.pm.common.utils.poi.ExcelUtilPageData;
import com.pm.repairOrder.service.IRepairOrderService;
import com.pm.common.utils.poi.ExcelUtil;
import com.pm.common.core.page.TableDataInfo;
import com.pm.common.utils.SecurityUtils;
import com.pm.common.utils.DateUtils;

/**
 * 维修工单Controller
 *
 * @author pm
 * @date 2025-04-27
 */
@RestController
@RequestMapping("/repairOrder/repairOrder")
public class RepairOrderController extends BaseController
{
    @Autowired
    private IRepairOrderService repairOrderService;

    /**
     * 查询维修工单列表
     */
    @PreAuthorize("@ss.hasPermi('repairOrder:repairOrder:list')")
    @GetMapping("/list")
    public TableDataInfo list()
    {
        PageData pd = this.getPageData();
        //startPage();
        List<PageData> list = repairOrderService.selectRepairOrderList(pd);
        return getDataTable(list);
    }

    /**
     * 导出维修工单列表
     */
    @PreAuthorize("@ss.hasPermi('repairOrder:repairOrder:export')")
    @Log(title = "维修工单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response)
    {
        try {
            PageData pd = this.getPageData();
            List<PageData> list = repairOrderService.selectRepairOrderList(pd);
            String filename = "维修工单数据";
            String[] titles = {
                    "序号,id",
                    "工单编号,orderNo",
                    "工单内容,orderContent",
                    "项目名称,projectName",
                    "派单时间,assignTime",
                    "完成时间,finishTime",
                    "完成人,finishBy",
                    "附件,annex",
                    "完成人id,userId",
                    "工单状态,orderStatus",
                    "工单备注,orderRemark"
            };
            ExcelUtilPageData.exportXLSX(response, null, null, filename, titles, list);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 获取维修工单详细信息
     */
    @PreAuthorize("@ss.hasPermi('repairOrder:repairOrder:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(repairOrderService.selectRepairOrderById(id));
    }

    /**
     * 新增维修工单
     */
    @PreAuthorize("@ss.hasPermi('repairOrder:repairOrder:add')")
    @Log(title = "维修工单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PageData pd)
    {
        // 设置创建信息
        pd.put("createBy", SecurityUtils.getUsername());
        pd.put("createTime", DateUtils.getNowDate());
        pd.put("orderStatus", pd.getString("orderStatus") == null ? "0" : pd.getString("orderStatus"));

        // 记录操作日志
        int result = repairOrderService.insertRepairOrder(pd);
        if (result > 0) {
            // 添加操作日志
            PageData logPd = new PageData();
            logPd.put("orderId", pd.getString("id"));
            logPd.put("operateDesc", "创建了工单");
            logPd.put("operateType", "create");
            repairOrderService.addOperationLog(logPd);
        }
        return toAjax(result);
    }

    /**
     * 修改维修工单
     */
    @PreAuthorize("@ss.hasPermi('repairOrder:repairOrder:edit')")
    @Log(title = "维修工单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PageData pd)
    {
        // 获取原工单信息
        PageData oldOrder = repairOrderService.selectRepairOrderById(pd.getString("id"));

        // 设置更新信息
        pd.put("updateBy", SecurityUtils.getUsername());
        pd.put("updateTime", DateUtils.getNowDate());

        int result = repairOrderService.updateRepairOrder(pd);

        if (result > 0) {
            // 记录操作日志
            PageData logPd = new PageData();
            logPd.put("orderId", pd.getString("id"));

            // 判断操作类型
            if (oldOrder.getString("userId") == null && pd.getString("userId") != null) {
                // 派单操作
                logPd.put("operateDesc", "派单给 " + pd.getString("finishBy"));
                logPd.put("operateType", "assign");
            } else if ("2".equals(pd.getString("orderStatus")) && !"2".equals(oldOrder.getString("orderStatus"))) {
                // 完成操作
                logPd.put("operateDesc", "完成了工单");
                logPd.put("operateType", "complete");
            } else {
                // 普通更新
                logPd.put("operateDesc", "更新了工单信息");
                logPd.put("operateType", "update");
            }

            repairOrderService.addOperationLog(logPd);
        }

        return toAjax(result);
    }

    /**
     * 删除维修工单
     */
    @PreAuthorize("@ss.hasPermi('repairOrder:repairOrder:remove')")
    @Log(title = "维修工单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(repairOrderService.deleteRepairOrderByIds(ids));
    }

    /**
     * 获取工单统计数据
     */
    @GetMapping("/statistics")
    public AjaxResult getStatistics()
    {
        PageData pd = this.getPageData();
        Map<String, Object> statistics = repairOrderService.getRepairOrderStatistics(pd);
        return success(statistics);
    }

    /**
     * 获取工单操作日志
     */
    @GetMapping("/logs/{orderId}")
    public AjaxResult getOperationLogs(@PathVariable String orderId)
    {
        PageData pd = new PageData();
        pd.put("orderId", orderId);
        List<PageData> logs = repairOrderService.getRepairOrderLogs(pd);
        return success(logs);
    }

    /**
     * 生成工单编号
     */
    @GetMapping("/generateOrderNo")
    public AjaxResult generateOrderNo()
    {
        String orderNo = repairOrderService.generateOrderNo();
        Map<String, String> result = new HashMap<>();
        result.put("orderNo", orderNo);
        return success(result);
    }

    /**
     * 删除文件
     */
    @DeleteMapping("/deleteFile")
    public AjaxResult deleteFile(String fileName)
    {
        try {
            // 这里调用文件删除服务
            return success("文件删除成功");
        } catch (Exception e) {
            return error("文件删除失败");
        }
    }
}
