Przeglądaj źródła

feature:组织管理-生产组织-工厂提交

yingjian.wu 4 miesięcy temu
rodzic
commit
d8563888cf

+ 63 - 0
src/main/java/com/qlm/common/ApiResponse.java

@@ -0,0 +1,63 @@
+package com.qlm.common;
+
+/**
+ * API 统一响应对象
+ */
+public class ApiResponse {
+    private int code;
+    private String msg;
+    private Object data;
+
+    public ApiResponse() {
+        this.code = 0;
+        this.msg = "成功";
+    }
+
+    public static ApiResponse success() {
+        return new ApiResponse();
+    }
+
+    public static ApiResponse success(Object data) {
+        ApiResponse response = new ApiResponse();
+        response.setData(data);
+        return response;
+    }
+
+    public static ApiResponse error(String msg) {
+        ApiResponse response = new ApiResponse();
+        response.setCode(500);
+        response.setMsg(msg);
+        return response;
+    }
+
+    public static ApiResponse error(int code, String msg) {
+        ApiResponse response = new ApiResponse();
+        response.setCode(code);
+        response.setMsg(msg);
+        return response;
+    }
+
+    public int getCode() {
+        return code;
+    }
+
+    public void setCode(int code) {
+        this.code = code;
+    }
+
+    public String getMsg() {
+        return msg;
+    }
+
+    public void setMsg(String msg) {
+        this.msg = msg;
+    }
+
+    public Object getData() {
+        return data;
+    }
+
+    public void setData(Object data) {
+        this.data = data;
+    }
+}

+ 69 - 0
src/main/java/com/qlm/common/PageResult.java

@@ -0,0 +1,69 @@
+package com.qlm.common;
+
+import java.util.List;
+
+/**
+ * @program: scanCode
+ * @ClassName: PageResult
+ * @description: TODO
+ * @author: 分页结果返回
+ * @create: 2025-07-24 11:38
+ * @Version 1.0
+ **/
+public class PageResult<T> {
+    private long total;       // 总记录数
+    private int pageSize;     // 每页条数
+    private int pageNum;      // 当前页码
+    private List<T> records;  // 当前页数据列表
+
+    public PageResult() {}
+
+    public PageResult(long total, int pageNum, int pageSize, List<T> records) {
+        this.total = total;
+        this.pageNum = pageNum;
+        this.pageSize = pageSize;
+        this.records = records;
+    }
+
+    public long getTotal() {
+        return total;
+    }
+
+    public void setTotal(long total) {
+        this.total = total;
+    }
+
+    public int getPageSize() {
+        return pageSize;
+    }
+
+    public void setPageSize(int pageSize) {
+        this.pageSize = pageSize;
+    }
+
+    public int getPageNum() {
+        return pageNum;
+    }
+
+    public void setPageNum(int pageNum) {
+        this.pageNum = pageNum;
+    }
+
+    public List<T> getRecords() {
+        return records;
+    }
+
+    public void setRecords(List<T> records) {
+        this.records = records;
+    }
+
+    @Override
+    public String toString() {
+        return "PageResult{" +
+                "total=" + total +
+                ", pageSize=" + pageSize +
+                ", pageNum=" + pageNum +
+                ", records=" + records +
+                '}';
+    }
+}

+ 176 - 0
src/main/java/com/qlm/controller/organize/FactoryController.java

@@ -0,0 +1,176 @@
+package com.qlm.controller.organize;
+
+import com.jfinal.kit.HttpKit;
+import com.qlm.annotation.RequestUrl;
+import com.qlm.common.ApiResponse;
+import com.qlm.controller.common.CommonUserController;
+import com.qlm.dto.FactoryDto;
+import com.qlm.service.IFactoryService;
+import com.qlm.service.impl.FactoryServiceImpl;
+import com.qlm.tools.WxUtil;
+import com.alibaba.fastjson.JSON;
+import com.qlm.view.core.AdminView;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * @author wuyingjianwu
+ * @date 2025/08/19
+ * 工厂信息管理
+ */
+@RequestUrl("/factory")
+public class FactoryController extends CommonUserController {
+    private static final Logger logger = LoggerFactory.getLogger(FactoryController.class);
+    private final IFactoryService factoryService = new FactoryServiceImpl();
+
+    public void getFactoryList() {
+        renderJsp("/page/jinzai/factory.jsp");
+    }
+
+    /**
+     * 保存工厂信息
+     */
+    @Override
+    public void save() {
+        AdminView loginUser = getLoginUser();
+        ApiResponse apiResponse;
+        try {
+            // 使用HttpKit.readData获取请求Body
+            String bodyData = HttpKit.readData(getRequest());
+            // 将JSON字符串转换为FactoryDto对象
+            FactoryDto factoryDto = JSON.parseObject(bodyData, FactoryDto.class);
+
+            // 数据验证
+            if (WxUtil.isNull(factoryDto.getFactoryCode())) {
+                apiResponse = ApiResponse.error("工厂编码不能为空");
+                renderJson(apiResponse);
+                return;
+            }
+
+            if (WxUtil.isNull(factoryDto.getFactoryName())) {
+                apiResponse = ApiResponse.error("工厂名称不能为空");
+                renderJson(apiResponse);
+                return;
+            }
+
+            // 调用Service层保存数据
+            apiResponse = factoryService.saveFactory(factoryDto);
+        } catch (Exception e) {
+            logger.error("系统异常:", e);
+            apiResponse = ApiResponse.error("系统异常:" + e.getMessage());
+        }
+        renderJson(apiResponse);
+    }
+
+    /**
+     * 更新工厂信息
+     */
+    public void update() {
+        ApiResponse apiResponse;
+        try {
+            String bodyData = HttpKit.readData(getRequest());
+            FactoryDto factoryDto = JSON.parseObject(bodyData, FactoryDto.class);
+
+            if (factoryDto.getId() == null) {
+                apiResponse = ApiResponse.error("工厂ID不能为空");
+                renderJson(apiResponse);
+                return;
+            }
+
+            apiResponse = factoryService.updateFactory(factoryDto);
+        } catch (Exception e) {
+            logger.error("系统异常:", e);
+            apiResponse = ApiResponse.error("系统异常:" + e.getMessage());
+        }
+        renderJson(apiResponse);
+    }
+
+    /**
+     * 删除工厂信息
+     */
+    public void delete() {
+        ApiResponse apiResponse = ApiResponse.success();
+        try {
+            Integer id = getParaToInt("id");
+            if (id == null) {
+                renderJson("status", 0);
+                renderJson("msg", "工厂ID不能为空");
+                return;
+            }
+
+            apiResponse = factoryService.deleteFactory(id);
+        } catch (Exception e) {
+            logger.error("系统异常:", e);
+            apiResponse = ApiResponse.error("系统异常:" + e.getMessage());
+        }
+        renderJson(apiResponse);
+    }
+
+    /**
+     * 根据ID获取工厂信息
+     */
+    @Override
+    public void getById() {
+        ApiResponse apiResponse;
+        try {
+            Integer id = getParaToInt("id");
+            if (id == null) {
+                renderJson("status", 0);
+                renderJson("msg", "工厂ID不能为空");
+                return;
+            }
+
+            apiResponse = factoryService.getFactoryById(id);
+        } catch (Exception e) {
+            logger.error("系统异常:", e);
+            apiResponse = ApiResponse.error("系统异常:" + e.getMessage());
+        }
+        renderJson(apiResponse);
+    }
+
+    /**
+     * 切换工厂状态
+     */
+    public void toggleStatus() {
+        ApiResponse apiResponse;
+        try {
+            Integer id = getParaToInt("id");
+            Integer status = getParaToInt("status");
+
+            if (id == null) {
+                renderJson("status", 0);
+                renderJson("msg", "工厂ID不能为空");
+                return;
+            }
+
+            if (status == null) {
+                renderJson("status", 0);
+                renderJson("msg", "状态值不能为空");
+                return;
+            }
+
+            apiResponse = factoryService.toggleFactoryStatus(id, status);
+        } catch (Exception e) {
+            logger.error("系统异常:", e);
+            apiResponse = ApiResponse.error("系统异常:" + e.getMessage());
+        }
+        renderJson(apiResponse);
+    }
+
+    /**
+     * 工厂列表查询
+     */
+    @Override
+    public void list() {
+        AdminView loginUser = getLoginUser();
+        // 获取分页参数
+        int pageNumber = getParaToInt("pageNumber", 1);
+        int pageSize = getParaToInt("pageSize", 10);
+        // 获取查询条件
+        String factoryName = getPara("factoryName");
+        String factoryCode = getPara("factoryCode");
+        // 调用Service层查询列表
+        renderJson(factoryService.listFactory(pageNumber, pageSize, factoryName, factoryCode));
+    }
+
+}

+ 185 - 0
src/main/java/com/qlm/dto/FactoryDto.java

@@ -0,0 +1,185 @@
+package com.qlm.dto;
+
+import java.io.Serializable;
+
+/**
+ * 工厂信息DTO
+ */
+public class FactoryDto implements Serializable {
+    private static final long serialVersionUID = 1L;
+
+    /**
+     * 主键
+     */
+    private Integer id;
+    /**
+     * 工厂编码
+     */
+    private String factoryCode;
+    /**
+     * 工厂名称
+     */
+    private String factoryName;
+    /**
+     * 联系人
+     */
+    private String contactPerson;
+    /**
+     * 联系电话
+     */
+    private String contactPhone;
+    /**
+     * 地址
+     */
+    private String address;
+    /**
+     * 状态 0停用 1启用
+     */
+    private Integer status;
+
+    /**
+     * 企业网址
+     */
+    private String website;
+
+    /**
+     * 邮政编码
+     */
+    private String postalCode;
+
+    /**
+     * 详细地址
+     */
+    private String addressDetail;
+
+    /**
+     * 省市区拼接
+     */
+    private String provinceCityDistrict;
+
+    /**
+     * 售后服务电话
+     */
+    private String servicePhone;
+
+    /**
+     * 操作人
+     */
+    private Integer operator;
+    /**
+     * 操作人名称
+     */
+    private String operateName;
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public String getFactoryCode() {
+        return factoryCode;
+    }
+
+    public void setFactoryCode(String factoryCode) {
+        this.factoryCode = factoryCode;
+    }
+
+    public String getFactoryName() {
+        return factoryName;
+    }
+
+    public void setFactoryName(String factoryName) {
+        this.factoryName = factoryName;
+    }
+
+    public String getContactPerson() {
+        return contactPerson;
+    }
+
+    public void setContactPerson(String contactPerson) {
+        this.contactPerson = contactPerson;
+    }
+
+    public String getContactPhone() {
+        return contactPhone;
+    }
+
+    public void setContactPhone(String contactPhone) {
+        this.contactPhone = contactPhone;
+    }
+
+    public String getAddress() {
+        return address;
+    }
+
+    public void setAddress(String address) {
+        this.address = address;
+    }
+
+    public Integer getStatus() {
+        return status;
+    }
+
+    public void setStatus(Integer status) {
+        this.status = status;
+    }
+
+    public Integer getOperator() {
+        return operator;
+    }
+
+    public void setOperator(Integer operator) {
+        this.operator = operator;
+    }
+
+    public String getOperateName() {
+        return operateName;
+    }
+
+    public void setOperateName(String operateName) {
+        this.operateName = operateName;
+    }
+
+    public String getWebsite() {
+        return website;
+    }
+
+    public void setWebsite(String website) {
+        this.website = website;
+    }
+
+    public String getPostalCode() {
+        return postalCode;
+    }
+
+    public void setPostalCode(String postalCode) {
+        this.postalCode = postalCode;
+    }
+
+    public String getAddressDetail() {
+        return addressDetail;
+    }
+
+    public void setAddressDetail(String addressDetail) {
+        this.addressDetail = addressDetail;
+    }
+
+    public String getProvinceCityDistrict() {
+        return provinceCityDistrict;
+    }
+
+    public void setProvinceCityDistrict(String provinceCityDistrict) {
+        this.provinceCityDistrict = provinceCityDistrict;
+    }
+
+    public String getServicePhone() {
+        return servicePhone;
+    }
+
+    public void setServicePhone(String servicePhone) {
+        this.servicePhone = servicePhone;
+    }
+}

+ 3 - 3
src/main/java/com/qlm/jfinal/JfinalConfig.java

@@ -41,7 +41,7 @@ public class JfinalConfig extends JFinalConfig {
 	
 	
 	@Override
 	@Override
 	public void configConstant(Constants me) {
 	public void configConstant(Constants me) {
-		me.setDevMode(false);
+		me.setDevMode(true);
 		me.setViewType(ViewType.JSP);
 		me.setViewType(ViewType.JSP);
 		me.setLogFactory(new LogerFactory());
 		me.setLogFactory(new LogerFactory());
 		PropKit.use("config.properties");
 		PropKit.use("config.properties");
@@ -107,8 +107,8 @@ public class JfinalConfig extends JFinalConfig {
 		arp.addMapping("t_qcode_hb_config_rate", AreaHbConfigRate.class);
 		arp.addMapping("t_qcode_hb_config_rate", AreaHbConfigRate.class);
 		arp.addMapping("t_master", Master.class);
 		arp.addMapping("t_master", Master.class);
 		arp.addMapping("t_res", Res.class);
 		arp.addMapping("t_res", Res.class);
-		arp.setShowSql(false);
-		arp.setDevMode(false);
+		arp.setShowSql(true);
+		arp.setDevMode(true);
 //		arp1.setShowSql(false);
 //		arp1.setShowSql(false);
 //		arp1.setDevMode(true);
 //		arp1.setDevMode(true);
 	}
 	}

+ 14 - 0
src/main/java/com/qlm/service/IFactoryService.java

@@ -0,0 +1,14 @@
+package com.qlm.service;
+
+import com.qlm.common.ApiResponse;
+import com.qlm.common.PageResult;
+import com.qlm.dto.FactoryDto;
+
+public interface IFactoryService {
+    ApiResponse saveFactory(FactoryDto factoryDto);
+    ApiResponse updateFactory(FactoryDto factoryDto);
+    ApiResponse deleteFactory(Integer id);
+    ApiResponse getFactoryById(Integer id);
+    ApiResponse toggleFactoryStatus(Integer id, Integer status);
+    PageResult<FactoryDto> listFactory(int pageNumber, int pageSize, String factoryName, String factoryCode);
+}

+ 210 - 0
src/main/java/com/qlm/service/impl/FactoryServiceImpl.java

@@ -0,0 +1,210 @@
+package com.qlm.service.impl;
+
+import com.jfinal.kit.StrKit;
+import com.jfinal.plugin.activerecord.Db;
+import com.jfinal.plugin.activerecord.Page;
+import com.jfinal.plugin.activerecord.Record;
+import com.qlm.common.ApiResponse;
+import com.qlm.common.PageResult;
+import com.qlm.controller.organize.FactoryController;
+import com.qlm.dto.FactoryDto;
+import com.qlm.service.IFactoryService;
+import com.qlm.tools.WxUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class FactoryServiceImpl implements IFactoryService {
+    private static final Logger logger = LoggerFactory.getLogger(FactoryServiceImpl.class);
+    @Override
+    public ApiResponse saveFactory(FactoryDto factoryDto) {
+        try {
+            //编码不能重复
+            Record factory = Db.findFirst("select * from t_factory where factory_code = ?", factoryDto.getFactoryCode());
+            if (factory != null) {
+                return ApiResponse.error("工厂编码已存在");
+            }
+            Record record = new Record();
+            record.set("factory_code", factoryDto.getFactoryCode());
+            record.set("factory_name", factoryDto.getFactoryName());
+            record.set("contact_name", factoryDto.getContactPerson());
+            record.set("contact_phone", factoryDto.getContactPhone());
+            record.set("factory_address", factoryDto.getAddress());
+            record.set("status", factoryDto.getStatus() != null ? factoryDto.getStatus() : 1);
+            if(StrKit.notBlank(factoryDto.getProvinceCityDistrict())){
+                //根据/切割 省市区
+                String[] split = factoryDto.getProvinceCityDistrict().split("-");
+                record.set("province", split[0]);
+                record.set("city", split[1]);
+                record.set("county", split[2]);
+            }
+            record.set("website", factoryDto.getWebsite());
+            record.set("postal_code", factoryDto.getPostalCode());
+            record.set("detail_address", factoryDto.getAddressDetail());
+            record.set("service_phone", factoryDto.getServicePhone());
+
+            boolean save = Db.save("t_factory", record);
+            if (save) {
+                return ApiResponse.success();
+            } else {
+                return ApiResponse.error("保存失败");
+            }
+        } catch (Exception e) {
+            logger.error("系统异常:", e);
+            return ApiResponse.error("系统异常");
+        }
+    }
+
+    @Override
+    public ApiResponse updateFactory(FactoryDto factoryDto) {
+        try {
+            //编码不能重复,除去自己
+            Record factory = Db.findFirst("select * from t_factory where factory_code = ? and id != ?", factoryDto.getFactoryCode(), factoryDto.getId());
+            if (factory != null) {
+                return ApiResponse.error("工厂编码已存在");
+            }
+            Record record = new Record();
+            record.set("id", factoryDto.getId());
+            record.set("factory_code", factoryDto.getFactoryCode());
+            record.set("factory_name", factoryDto.getFactoryName());
+            record.set("contact_name", factoryDto.getContactPerson());
+            record.set("contact_phone", factoryDto.getContactPhone());
+            record.set("factory_address", factoryDto.getAddress());
+            record.set("status", factoryDto.getStatus());
+
+            if(StrKit.notBlank(factoryDto.getProvinceCityDistrict())){
+                //根据/切割 省市区
+                String[] split = factoryDto.getProvinceCityDistrict().split("-");
+                record.set("province", split[0]);
+                record.set("city", split[1]);
+                record.set("county", split[2]);
+            }
+            record.set("website", factoryDto.getWebsite());
+            record.set("postal_code", factoryDto.getPostalCode());
+            record.set("detail_address", factoryDto.getAddressDetail());
+            record.set("service_phone", factoryDto.getServicePhone());
+
+            boolean update = Db.update("t_factory", record);
+            if (update) {
+                return ApiResponse.success();
+            } else {
+                return ApiResponse.error("更新失败");
+            }
+        } catch (Exception e) {
+            logger.error("系统异常:", e);
+            return ApiResponse.error("系统异常");
+        }
+    }
+
+    @Override
+    public ApiResponse deleteFactory(Integer id) {
+        try {
+            boolean b = Db.deleteById("t_factory", id);
+            return b ? ApiResponse.success() : ApiResponse.error("删除失败");
+        } catch (Exception e) {
+            logger.error("系统异常:", e);
+            return ApiResponse.error("系统异常");
+        }
+    }
+
+    @Override
+    public ApiResponse getFactoryById(Integer id) {
+        try {
+            Record record = Db.findById("t_factory", id);
+            if (record == null) {
+                return null;
+            }
+            FactoryDto factoryDto = convertRecordToDto(record);
+            return ApiResponse.success(factoryDto);
+        } catch (Exception e) {
+            logger.error("系统异常:", e);
+            return ApiResponse.error("系统异常");
+        }
+    }
+
+    @Override
+    public ApiResponse toggleFactoryStatus(Integer id, Integer status) {
+        try {
+            Record record = new Record();
+            record.set("id", id);
+            record.set("status", status);
+            record.set("update_time", WxUtil.getNowTime());
+            boolean update = Db.update("t_factory", record);
+            return update ? ApiResponse.success() : ApiResponse.error("更新失败");
+        } catch (Exception e) {
+            logger.error("系统异常:", e);
+            return ApiResponse.error("系统异常");
+        }
+    }
+
+    @Override
+    public PageResult<FactoryDto> listFactory(int pageNumber, int pageSize, String factoryName, String factoryCode) {
+        try {
+            // 构建查询条件
+            StringBuilder sqlWhere = new StringBuilder(" from t_factory where 1=1 ");
+            List<Object> params = new ArrayList<>();
+
+            if (!WxUtil.isNull(factoryName)) {
+                sqlWhere.append(" and factory_name like ? ");
+                params.add("%" + factoryName + "%");
+            }
+
+            if (!WxUtil.isNull(factoryCode)) {
+                sqlWhere.append(" and factory_code like ? ");
+                params.add("%" + factoryCode + "%");
+            }
+
+            sqlWhere.append(" order by updated_time desc ");
+
+            // 执行分页查询
+            Page<Record> recordPage = Db.paginate(pageNumber, pageSize,
+                    "select * ",
+                    sqlWhere.toString(),
+                    params.toArray());
+
+            if (recordPage == null) {
+                return new PageResult<>(0, pageNumber, pageSize, new ArrayList<>());
+            }
+
+            // 转换为Dto对象
+            List<FactoryDto> factoryDtoList = new ArrayList<>();
+            for (Record record : recordPage.getList()) {
+                factoryDtoList.add(convertRecordToDto(record));
+            }
+
+            // 创建新的Page对象,包含Dto列表
+            return new PageResult<>(recordPage.getTotalRow(),
+                    recordPage.getPageNumber(),
+                    recordPage.getPageSize(),
+                    factoryDtoList);
+
+        } catch (Exception e) {
+            logger.error("系统异常:", e);
+            return new PageResult<>(0, pageNumber, pageSize, new ArrayList<>());
+        }
+    }
+
+    /**
+     * 将Record转换为FactoryDto的工具方法
+     * @param record
+     * @return
+     */
+    private FactoryDto convertRecordToDto(Record record) {
+        FactoryDto dto = new FactoryDto();
+        dto.setId(WxUtil.getInt("id",record));
+        dto.setFactoryCode(record.getStr("factory_code"));
+        dto.setFactoryName(record.getStr("factory_name"));
+        dto.setContactPerson(record.getStr("contact_name"));
+        dto.setContactPhone(record.getStr("contact_phone"));
+        dto.setAddress(record.getStr("address"));
+        dto.setStatus(record.getInt("status"));
+        dto.setProvinceCityDistrict(record.getStr("province") + "-" + record.getStr("city") + "-" + record.getStr("county"));
+        dto.setWebsite(record.getStr("website"));
+        dto.setPostalCode(record.getStr("postal_code"));
+        dto.setAddressDetail(record.getStr("detail_address"));
+        dto.setServicePhone(record.getStr("service_phone"));
+        return dto;
+    }
+}

+ 268 - 0
src/main/java/com/qlm/service/impl/WorkshopServiceImpl.java

@@ -0,0 +1,268 @@
+package com.qlm.service.impl;
+
+import com.jfinal.kit.StrKit;
+import com.jfinal.plugin.activerecord.Db;
+import com.jfinal.plugin.activerecord.Page;
+import com.jfinal.plugin.activerecord.Record;
+import com.qlm.common.ApiResponse;
+import com.qlm.common.PageResult;
+import com.qlm.dto.WorkshopDto;
+import com.qlm.service.IWorkshopService;
+import com.qlm.tools.WxUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @author wuyingjianwu
+ * @date 2025/08/19
+ * @description: 车间服务实现类
+ */
+public class WorkshopServiceImpl implements IWorkshopService {
+
+    private static final Logger logger = LoggerFactory.getLogger(WorkshopServiceImpl.class);
+
+    @Override
+    public ApiResponse saveWorkshop(WorkshopDto workshopDto) {
+        try {
+            // 数据验证
+            if (StrKit.isBlank(workshopDto.getWorkshopCode())) {
+                return ApiResponse.error("车间编号不能为空");
+            }
+
+            if (StrKit.isBlank(workshopDto.getWorkshopName())) {
+                return ApiResponse.error("车间名称不能为空");
+            }
+
+            if (workshopDto.getFactoryId() == null) {
+                return ApiResponse.error("所属工厂不能为空");
+            }
+
+            // 检查车间编号是否已存在
+            Record existRecord = Db.findFirst("select id from t_workshop where workshop_code = ?", workshopDto.getWorkshopCode());
+            if (existRecord != null) {
+                return ApiResponse.error("车间编号已存在");
+            }
+
+            // 保存数据
+            Record record = new Record();
+            record.set("workshop_code", workshopDto.getWorkshopCode());
+            record.set("workshop_name", workshopDto.getWorkshopName());
+            record.set("factory_id", workshopDto.getFactoryId());
+            record.set("contact_name", workshopDto.getContactName());
+            record.set("contact_phone", workshopDto.getContactPhone());
+            record.set("status", workshopDto.getStatus());
+
+
+            boolean result = Db.save("t_workshop", record);
+            if (result) {
+                return ApiResponse.success("保存成功");
+            } else {
+                return ApiResponse.error("保存失败");
+            }
+        } catch (Exception e) {
+            logger.error("保存车间信息异常:", e);
+            return ApiResponse.error("系统异常:" + e.getMessage());
+        }
+    }
+
+    @Override
+    public ApiResponse updateWorkshop(WorkshopDto workshopDto) {
+        try {
+            // 数据验证
+            if (workshopDto.getId() == null) {
+                return ApiResponse.error("车间ID不能为空");
+            }
+
+            if (StrKit.isBlank(workshopDto.getWorkshopCode())) {
+                return ApiResponse.error("车间编号不能为空");
+            }
+
+            if (StrKit.isBlank(workshopDto.getWorkshopName())) {
+                return ApiResponse.error("车间名称不能为空");
+            }
+
+            if (workshopDto.getFactoryId() == null) {
+                return ApiResponse.error("所属工厂不能为空");
+            }
+
+            // 检查车间编号是否已存在(排除当前记录)
+            Record existRecord = Db.findFirst("select id from t_workshop where workshop_code = ? and id != ?", 
+                    workshopDto.getWorkshopCode(), workshopDto.getId());
+            if (existRecord != null) {
+                return ApiResponse.error("车间编号已存在");
+            }
+
+            // 更新数据
+            Record record = new Record();
+            record.set("id", workshopDto.getId());
+            record.set("workshop_code", workshopDto.getWorkshopCode());
+            record.set("workshop_name", workshopDto.getWorkshopName());
+            record.set("factory_id", workshopDto.getFactoryId());
+            record.set("contact_name", workshopDto.getContactName());
+            record.set("contact_phone", workshopDto.getContactPhone());
+
+            boolean result = Db.update("t_workshop", record);
+            if (result) {
+                return ApiResponse.success("更新成功");
+            } else {
+                return ApiResponse.error("更新失败");
+            }
+        } catch (Exception e) {
+            logger.error("更新车间信息异常:", e);
+            return ApiResponse.error("系统异常:" + e.getMessage());
+        }
+    }
+
+    @Override
+    public ApiResponse deleteWorkshop(Long id) {
+        try {
+            if (id == null) {
+                return ApiResponse.error("车间ID不能为空");
+            }
+
+            // 检查是否存在关联数据(如果有)
+            // TODO: 如果有其他表关联到车间表,需要先检查并处理
+
+            boolean result = Db.deleteById("t_workshop", id);
+            if (result) {
+                return ApiResponse.success("删除成功");
+            } else {
+                return ApiResponse.error("删除失败");
+            }
+        } catch (Exception e) {
+            logger.error("删除车间信息异常:", e);
+            return ApiResponse.error("系统异常:" + e.getMessage());
+        }
+    }
+
+    @Override
+    public ApiResponse getWorkshopById(Long id) {
+        try {
+            if (id == null) {
+                return ApiResponse.error("车间ID不能为空");
+            }
+
+            // 关联查询工厂名称
+            String sql = "select w.*, f.factory_name from t_workshop w left join t_factory f on w.factory_id = f.id where w.id = ?";
+            Record record = Db.findFirst(sql, id);
+            if (record == null) {
+                return ApiResponse.error("未找到该车间信息");
+            }
+
+            WorkshopDto workshopDto = convertRecordToDto(record);
+            return ApiResponse.success(workshopDto);
+        } catch (Exception e) {
+            logger.error("获取车间信息异常:", e);
+            return ApiResponse.error("系统异常:" + e.getMessage());
+        }
+    }
+
+    @Override
+    public ApiResponse toggleWorkshopStatus(Long id, Integer status) {
+        try {
+            if (id == null) {
+                return ApiResponse.error("车间ID不能为空");
+            }
+
+            if (status == null || (status != 0 && status != 1)) {
+                return ApiResponse.error("状态值无效,只能是0或1");
+            }
+
+            Record record = new Record();
+            record.set("id", id);
+            record.set("status", status);
+
+            boolean result = Db.update("t_workshop", record);
+            if (result) {
+                return ApiResponse.success("状态更新成功");
+            } else {
+                return ApiResponse.error("状态更新失败");
+            }
+        } catch (Exception e) {
+            logger.error("切换车间状态异常:", e);
+            return ApiResponse.error("系统异常:" + e.getMessage());
+        }
+    }
+
+    @Override
+    public PageResult<WorkshopDto> listWorkshop(int pageNumber, int pageSize, String workshopName, Long factoryId) {
+        try {
+            // 构建查询条件
+            StringBuilder sqlWhere = new StringBuilder(" from t_workshop w left join t_factory f on w.factory_id = f.id where 1=1 ");
+            List<Object> params = new ArrayList<>();
+
+            if (StrKit.notBlank(workshopName)) {
+                sqlWhere.append(" and w.workshop_name like ? ");
+                params.add("%" + workshopName + "%");
+            }
+
+            if (factoryId != null) {
+                sqlWhere.append(" and w.factory_id = ? ");
+                params.add(factoryId);
+            }
+
+            // 执行分页查询
+            Page<Record> recordPage = Db.paginate(pageNumber, pageSize,
+                    "select w.*, f.factory_name ",
+                    sqlWhere.toString() + " order by w.updated_time desc ",
+                    params.toArray());
+
+            // 转换为Dto对象
+            List<WorkshopDto> workshopDtoList = new ArrayList<>();
+            for (Record record : recordPage.getList()) {
+                workshopDtoList.add(convertRecordToDto(record));
+            }
+
+            // 创建新的PageResult对象
+            return new PageResult<>(recordPage.getTotalRow(), pageNumber, pageSize, workshopDtoList);
+
+        } catch (Exception e) {
+            logger.error("查询车间列表异常:", e);
+            return new PageResult<>(0, pageNumber, pageSize, new ArrayList<>());
+        }
+    }
+
+    @Override
+    public ApiResponse getAllFactories() {
+        try {
+            // 查询所有启用的工厂
+            String sql = "select id, factory_name from t_factory where status = 1 order by factory_name asc";
+            List<Record> records = Db.find(sql);
+
+            List<Record> resultList = new ArrayList<>();
+            for (Record record : records) {
+                Record item = new Record();
+                item.set("value", record.getLong("id"));
+                item.set("label", record.getStr("factory_name"));
+                resultList.add(item);
+            }
+
+            return ApiResponse.success(resultList);
+        } catch (Exception e) {
+            logger.error("获取工厂列表异常:", e);
+            return ApiResponse.error("系统异常:" + e.getMessage());
+        }
+    }
+
+    /**
+     * 将Record转换为WorkshopDto的工具方法
+     */
+    private WorkshopDto convertRecordToDto(Record record) {
+        WorkshopDto dto = new WorkshopDto();
+        dto.setId(record.getLong("id"));
+        dto.setWorkshopCode(record.getStr("workshop_code"));
+        dto.setWorkshopName(record.getStr("workshop_name"));
+        dto.setFactoryId(record.getLong("factory_id"));
+        dto.setFactoryName(record.getStr("factory_name"));
+        dto.setContactName(record.getStr("contact_name"));
+        dto.setContactPhone(record.getStr("contact_phone"));
+        dto.setStatus(record.getInt("status"));
+        dto.setCreatedTime(record.getDate("created_time"));
+        dto.setUpdatedTime(record.getDate("updated_time"));
+        dto.setOperator(record.getStr("operator"));
+        return dto;
+    }
+}

Plik diff jest za duży
+ 3804 - 0
src/main/webapp/common/area.json


+ 632 - 0
src/main/webapp/page/dealerManagement.jsp

@@ -0,0 +1,632 @@
+<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
+<!DOCTYPE html>
+<html lang="zh-CN">
+<head>
+    <meta charset="UTF-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <title>经销商管理</title>
+    <!-- 引入Bootstrap CSS -->
+    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
+    <!-- 引入Font Awesome图标 -->
+    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
+    <style>
+        .status-normal {
+            color: green;
+            font-weight: bold;
+        }
+        .status-disabled {
+            color: red;
+            font-weight: bold;
+        }
+        .action-link {
+            margin-right: 8px;
+            text-decoration: none;
+        }
+        .action-edit {
+            color: #0d6efd;
+        }
+        .action-delete {
+            color: #dc3545;
+        }
+        .pagination-container {
+            display: flex;
+            justify-content: flex-end;
+            align-items: center;
+        }
+        .pagination .page-item.active .page-link {
+            background-color: #0d6efd;
+            border-color: #0d6efd;
+        }
+        .dealer-name {
+            color: #0d6efd;
+            cursor: pointer;
+            text-decoration: underline;
+        }
+        .modal-body .form-group {
+            margin-bottom: 1rem;
+        }
+        .selected-area {
+            background-color: #e9ecef;
+            padding: 0.5rem;
+            border-radius: 0.25rem;
+            margin-bottom: 0.5rem;
+            display: flex;
+            flex-wrap: wrap;
+            gap: 0.5rem;
+        }
+        .area-tag {
+            background-color: #0d6efd;
+            color: white;
+            padding: 0.25rem 0.5rem;
+            border-radius: 0.25rem;
+            display: flex;
+            align-items: center;
+        }
+        .area-tag .remove-area {
+            margin-left: 0.5rem;
+            cursor: pointer;
+        }
+    </style>
+</head>
+<body>
+    <div class="container mt-4">
+        <div class="card">
+            <div class="card-header bg-primary text-white">
+                <h4 class="mb-0">经销商管理</h4>
+            </div>
+            <div class="card-body">
+                <!-- 搜索区域 -->
+                <div class="search-area mb-4 d-flex flex-wrap gap-2">
+                    <div class="flex-grow-1">
+                        <input type="text" class="form-control" id="dealerCode" placeholder="请输入经销商编号">
+                    </div>
+                    <div class="flex-grow-1">
+                        <input type="text" class="form-control" id="dealerName" placeholder="请输入经销商名称">
+                    </div>
+                    <button type="button" class="btn btn-primary" id="searchBtn">
+                        <i class="fas fa-search me-1"></i> 查询
+                    </button>
+                    <button type="button" class="btn btn-secondary" id="resetBtn">
+                        <i class="fas fa-sync-alt me-1"></i> 重置
+                    </button>
+                </div>
+
+                <!-- 操作按钮区域 -->
+                <div class="action-buttons mb-4 d-flex justify-content-end gap-2">
+                    <button type="button" class="btn btn-success" id="addBtn">
+                        <i class="fas fa-plus me-1"></i> 新增
+                    </button>
+                    <button type="button" class="btn btn-info" id="importBtn">
+                        <i class="fas fa-upload me-1"></i> 导入
+                    </button>
+                    <button type="button" class="btn btn-warning" id="exportBtn">
+                        <i class="fas fa-download me-1"></i> 导出
+                    </button>
+                </div>
+
+                <!-- 数据表格 -->
+                <div class="table-responsive">
+                    <table class="table table-striped table-hover">
+                        <thead class="table-light">
+                            <tr>
+                                <th><input type="checkbox" id="selectAll"></th>
+                                <th>经销商编号</th>
+                                <th>经销商名称</th>
+                                <th>联系人</th>
+                                <th>联系方式</th>
+                                <th>状态</th>
+                                <th>操作</th>
+                            </tr>
+                        </thead>
+                        <tbody id="dealerTableBody">
+                            <!-- 表格数据将通过JavaScript动态加载 -->
+                        </tbody>
+                    </table>
+                </div>
+
+                <!-- 分页控件 -->
+                <div class="pagination-container mt-4">
+                    <nav aria-label="Page navigation">
+                        <ul class="pagination">
+                            <li class="page-item">
+                                <a class="page-link" href="#" aria-label="Previous">
+                                    <span aria-hidden="true">&lt;</span>
+                                </a>
+                            </li>
+                            <li class="page-item active"><a class="page-link" href="#">1</a></li>
+                            <li class="page-item"><a class="page-link" href="#">2</a></li>
+                            <li class="page-item"><a class="page-link" href="#">3</a></li>
+                            <li class="page-item"><a class="page-link" href="#">4</a></li>
+                            <li class="page-item"><a class="page-link" href="#">5</a></li>
+                            <li class="page-item disabled"><span class="page-link">...</span></li>
+                            <li class="page-item"><a class="page-link" href="#">10</a></li>
+                            <li class="page-item">
+                                <a class="page-link" href="#" aria-label="Next">
+                                    <span aria-hidden="true">&gt;</span>
+                                </a>
+                            </li>
+                        </ul>
+                    </nav>
+                </div>
+            </div>
+        </div>
+    </div>
+
+    <!-- 详情模态框 -->
+    <div class="modal fade" id="detailModal" tabindex="-1" aria-labelledby="detailModalLabel" aria-hidden="true">
+        <div class="modal-dialog modal-lg">
+            <div class="modal-content">
+                <div class="modal-header bg-primary text-white">
+                    <h5 class="modal-title" id="detailModalLabel">经销商详情</h5>
+                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
+                </div>
+                <div class="modal-body" id="detailModalBody">
+                    <!-- 详情内容将通过JavaScript动态加载 -->
+                </div>
+                <div class="modal-footer">
+                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
+                </div>
+            </div>
+        </div>
+    </div>
+
+    <!-- 新增/编辑模态框 -->
+    <div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
+        <div class="modal-dialog modal-lg">
+            <div class="modal-content">
+                <div class="modal-header bg-primary text-white">
+                    <h5 class="modal-title" id="editModalLabel">新增经销商</h5>
+                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
+                </div>
+                <div class="modal-body">
+                    <form id="dealerForm">
+                        <input type="hidden" id="dealerId" name="dealerId">
+                        <div class="row">
+                            <div class="col-md-6">
+                                <div class="form-group">
+                                    <label for="editDealerCode" class="required">经销商编号</label>
+                                    <input type="text" class="form-control" id="editDealerCode" name="editDealerCode" placeholder="请输入" required>
+                                </div>
+                                <div class="form-group">
+                                    <label for="editContactPerson" class="required">联系人</label>
+                                    <input type="text" class="form-control" id="editContactPerson" name="editContactPerson" placeholder="请输入" required>
+                                </div>
+                            </div>
+                            <div class="col-md-6">
+                                <div class="form-group">
+                                    <label for="editDealerName" class="required">经销商名称</label>
+                                    <input type="text" class="form-control" id="editDealerName" name="editDealerName" placeholder="请输入" required>
+                                    <small class="form-text text-muted">名称:不超过50个字符</small>
+                                </div>
+                                <div class="form-group">
+                                    <label for="editContactInfo" class="required">联系方式</label>
+                                    <input type="text" class="form-control" id="editContactInfo" name="editContactInfo" placeholder="请输入" required>
+                                </div>
+                            </div>
+                        </div>
+                        <div class="form-group">
+                            <label for="editSalesArea" class="required">销售地区</label>
+                            <div class="selected-area" id="selectedArea">
+                                <!-- 选中的地区将在这里显示 -->
+                            </div>
+                            <select class="form-select" id="areaSelect">
+                                <option value="">请选择销售地区</option>
+                                <option value="湖南省/长沙市">湖南省/长沙市</option>
+                                <option value="湖南省/益阳市">湖南省/益阳市</option>
+                                <option value="湖南省/岳阳市">湖南省/岳阳市</option>
+                                <option value="湖南省/株洲市">湖南省/株洲市</option>
+                                <option value="湖南省/湘潭市">湖南省/湘潭市</option>
+                                <option value="湖北省/武汉市">湖北省/武汉市</option>
+                                <option value="东南/上海/普陀">东南/上海/普陀</option>
+                                <option value="东南/上海/黄浦">东南/上海/黄浦</option>
+                            </select>
+                            <button type="button" class="btn btn-sm btn-primary mt-2" id="addAreaBtn">添加地区</button>
+                            <small class="form-text text-muted">销售地区:省-市,可多选</small>
+                        </div>
+                        <div class="form-group">
+                            <label for="editStatus" class="required">状态</label>
+                            <label class="toggle-switch">
+                                <input type="checkbox" id="editStatus" name="editStatus" checked>
+                                <span class="slider"></span>
+                            </label>
+                            <span id="statusText" class="ms-2">正常</span>
+                        </div>
+                    </form>
+                </div>
+                <div class="modal-footer">
+                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
+                    <button type="button" class="btn btn-primary" id="saveBtn">确定</button>
+                </div>
+            </div>
+        </div>
+    </div>
+
+    <!-- 引入jQuery -->
+    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
+    <!-- 引入Bootstrap JS -->
+    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
+
+    <script>
+        $(document).ready(function() {
+            // 模拟经销商数据
+            const dealerData = [
+                {
+                    id: 'E353',
+                    name: '河北唐山常盛',
+                    contactPerson: '张建新',
+                    contactInfo: '-',
+                    status: 'normal',
+                    salesArea: ['湖南省/长沙市', '湖南省/益阳市', '湖南省/岳阳市'],
+                    creator: '张媛媛',
+                    createTime: '2025-03-12 12:00:00'
+                },
+                {
+                    id: 'E352',
+                    name: '云南大理常盛',
+                    contactPerson: '欧阳未央',
+                    contactInfo: '15988886666',
+                    status: 'normal',
+                    salesArea: ['云南省/大理市', '云南省/昆明市'],
+                    creator: '李娜',
+                    createTime: '2025-03-10 09:30:00'
+                },
+                {
+                    id: 'E350',
+                    name: '河北新乐张苗',
+                    contactPerson: '欧阳未央',
+                    contactInfo: '15988886666',
+                    status: 'normal',
+                    salesArea: ['河北省/石家庄市', '河北省/保定市'],
+                    creator: '王强',
+                    createTime: '2025-03-08 14:15:00'
+                },
+                {
+                    id: 'E344',
+                    name: '河南平原新区张苗',
+                    contactPerson: '王语嫣',
+                    contactInfo: '15988886666',
+                    status: 'disabled',
+                    salesArea: ['河南省/新乡市', '河南省/郑州市'],
+                    creator: '赵伟',
+                    createTime: '2025-03-05 16:45:00'
+                },
+                {
+                    id: 'E351',
+                    name: '河南平原新区张香苗',
+                    contactPerson: '欧阳未央',
+                    contactInfo: '15988886666',
+                    status: 'normal',
+                    salesArea: ['河南省/新乡市', '河南省/焦作市'],
+                    creator: '张媛媛',
+                    createTime: '2025-03-01 10:20:00'
+                }
+            ];
+
+            // 当前选中的地区
+            let selectedAreas = [];
+
+            // 初始化详情模态框
+            const detailModal = new bootstrap.Modal(document.getElementById('detailModal'));
+            // 初始化编辑模态框
+            const editModal = new bootstrap.Modal(document.getElementById('editModal'));
+
+            // 全选/取消全选功能
+            $('#selectAll').on('change', function() {
+                $('.dealerCheckbox').prop('checked', this.checked);
+            });
+
+            // 搜索按钮点击事件
+            $('#searchBtn').on('click', function() {
+                const dealerCode = $('#dealerCode').val().trim();
+                const dealerName = $('#dealerName').val().trim();
+                // 过滤数据
+                let filteredData = dealerData;
+                if (dealerCode) {
+                    filteredData = filteredData.filter(dealer => dealer.id.includes(dealerCode));
+                }
+                if (dealerName) {
+                    filteredData = filteredData.filter(dealer => dealer.name.includes(dealerName));
+                }
+                // 重新渲染表格
+                renderDealerTable(filteredData);
+            });
+
+            // 重置按钮点击事件
+            $('#resetBtn').on('click', function() {
+                $('#dealerCode').val('');
+                $('#dealerName').val('');
+                $('.dealerCheckbox').prop('checked', false);
+                $('#selectAll').prop('checked', false);
+                // 重新渲染表格
+                renderDealerTable(dealerData);
+            });
+
+            // 新增按钮点击事件
+            $('#addBtn').on('click', function() {
+                // 清空表单
+                $('#dealerForm')[0].reset();
+                $('#dealerId').val('');
+                $('#editModalLabel').text('新增经销商');
+                selectedAreas = [];
+                renderSelectedAreas();
+                // 显示模态框
+                editModal.show();
+            });
+
+            // 导入按钮点击事件
+            $('#importBtn').on('click', function() {
+                alert('导入功能待实现');
+            });
+
+            // 导出按钮点击事件
+            $('#exportBtn').on('click', function() {
+                alert('导出功能待实现');
+            });
+
+            // 保存按钮点击事件
+            $('#saveBtn').on('click', function() {
+                // 表单验证
+                if (!validateForm()) {
+                    return;
+                }
+
+                // 获取表单数据
+                const dealerId = $('#dealerId').val();
+                const dealerCode = $('#editDealerCode').val().trim();
+                const dealerName = $('#editDealerName').val().trim();
+                const contactPerson = $('#editContactPerson').val().trim();
+                const contactInfo = $('#editContactInfo').val().trim();
+                const status = $('#editStatus').is(':checked') ? 'normal' : 'disabled';
+                const salesArea = [...selectedAreas];
+
+                if (dealerId) {
+                    // 编辑现有经销商
+                    const index = dealerData.findIndex(dealer => dealer.id === dealerId);
+                    if (index !== -1) {
+                        dealerData[index] = {
+                            ...dealerData[index],
+                            id: dealerCode,
+                            name: dealerName,
+                            contactPerson: contactPerson,
+                            contactInfo: contactInfo,
+                            status: status,
+                            salesArea: salesArea
+                        };
+                        alert('编辑成功');
+                    }
+                } else {
+                    // 添加新经销商
+                    const newDealer = {
+                        id: dealerCode,
+                        name: dealerName,
+                        contactPerson: contactPerson,
+                        contactInfo: contactInfo,
+                        status: status,
+                        salesArea: salesArea,
+                        creator: '当前用户',
+                        createTime: new Date().toLocaleString()
+                    };
+                    dealerData.unshift(newDealer);
+                    alert('添加成功');
+                }
+
+                // 关闭模态框
+                editModal.hide();
+                // 重新渲染表格
+                renderDealerTable(dealerData);
+            });
+
+            // 添加地区按钮点击事件
+            $('#addAreaBtn').on('click', function() {
+                const area = $('#areaSelect').val();
+                if (area && !selectedAreas.includes(area)) {
+                    selectedAreas.push(area);
+                    renderSelectedAreas();
+                }
+            });
+
+            // 状态切换按钮
+            const statusToggle = document.getElementById('editStatus');
+            const statusText = document.getElementById('statusText');
+
+            statusToggle.addEventListener('change', function() {
+                if (this.checked) {
+                    statusText.textContent = '正常';
+                } else {
+                    statusText.textContent = '禁用';
+                }
+            });
+
+            // 渲染选中的地区
+            function renderSelectedAreas() {
+                const selectedAreaEl = document.getElementById('selectedArea');
+                selectedAreaEl.innerHTML = '';
+                selectedAreas.forEach(area => {
+                    const areaTag = document.createElement('div');
+                    areaTag.className = 'area-tag';
+                    areaTag.innerHTML = `${area} <span class="remove-area"><i class="fas fa-times"></i></span>`;
+                    areaTag.querySelector('.remove-area').addEventListener('click', function() {
+                        selectedAreas = selectedAreas.filter(a => a !== area);
+                        renderSelectedAreas();
+                    });
+                    selectedAreaEl.appendChild(areaTag);
+                });
+            }
+
+            // 表单验证
+            function validateForm() {
+                let isValid = true;
+
+                // 经销商编号验证
+                const dealerCode = $('#editDealerCode').val().trim();
+                if (!dealerCode) {
+                    alert('经销商编号不能为空');
+                    isValid = false;
+                }
+
+                // 经销商名称验证
+                const dealerName = $('#editDealerName').val().trim();
+                if (!dealerName) {
+                    alert('经销商名称不能为空');
+                    isValid = false;
+                } else if (dealerName.length > 50) {
+                    alert('经销商名称不能超过50个字符');
+                    isValid = false;
+                }
+
+                // 联系人验证
+                const contactPerson = $('#editContactPerson').val().trim();
+                if (!contactPerson) {
+                    alert('联系人不能为空');
+                    isValid = false;
+                }
+
+                // 联系方式验证
+                const contactInfo = $('#editContactInfo').val().trim();
+                if (!contactInfo) {
+                    alert('联系方式不能为空');
+                    isValid = false;
+                }
+
+                // 销售地区验证
+                if (selectedAreas.length === 0) {
+                    alert('请选择销售地区');
+                    isValid = false;
+                }
+
+                return isValid;
+            }
+
+            // 渲染经销商表格
+            function renderDealerTable(data) {
+                const tableBody = document.getElementById('dealerTableBody');
+                tableBody.innerHTML = '';
+
+                data.forEach(dealer => {
+                    const row = document.createElement('tr');
+                    row.innerHTML = `
+                        <td><input type="checkbox" class="dealerCheckbox" value="${dealer.id}"></td>
+                        <td>${dealer.id}</td>
+                        <td><span class="dealer-name" data-id="${dealer.id}">${dealer.name}</span></td>
+                        <td>${dealer.contactPerson}</td>
+                        <td>${dealer.contactInfo}</td>
+                        <td><span class="${dealer.status == 'normal' ? 'status-normal' : 'status-disabled'}">${dealer.status == 'normal' ? '正常' : '禁用'}</span></td>
+                        <td>
+                            <a href="#" class="action-link action-edit" data-id="${dealer.id}"><i class="fas fa-edit me-1"></i>编辑</a>
+                            <a href="#" class="action-link action-delete" data-id="${dealer.id}"><i class="fas fa-trash-alt me-1"></i>删除</a>
+                        </td>
+                    `;
+                    tableBody.appendChild(row);
+                });
+
+                // 为经销商名称添加点击事件
+                $('.dealer-name').on('click', function() {
+                    const dealerId = $(this).data('id');
+                    showDealerDetail(dealerId);
+                });
+
+                // 为编辑链接添加点击事件
+                $('.action-edit').on('click', function(e) {
+                    e.preventDefault();
+                    const dealerId = $(this).data('id');
+                    editDealer(dealerId);
+                });
+
+                // 为删除链接添加点击事件
+                $('.action-delete').on('click', function(e) {
+                    e.preventDefault();
+                    const dealerId = $(this).data('id');
+                    if (confirm('确定要删除经销商 ' + dealerId + ' 吗?')) {
+                        // 删除经销商
+                        const index = dealerData.findIndex(dealer => dealer.id === dealerId);
+                        if (index !== -1) {
+                            dealerData.splice(index, 1);
+                            // 重新渲染表格
+                            renderDealerTable(dealerData);
+                            alert('删除成功');
+                        }
+                    }
+                });
+            }
+
+            // 显示经销商详情
+            function showDealerDetail(dealerId) {
+                const dealer = dealerData.find(d => d.id === dealerId);
+                if (dealer) {
+                    const detailBody = document.getElementById('detailModalBody');
+                    detailBody.innerHTML = `
+                        <div class="row mb-3">
+                            <div class="col-md-6">
+                                <p><strong>经销商编码:</strong>${dealer.id}</p>
+                            </div>
+                            <div class="col-md-6">
+                                <p><strong>经销商名称:</strong>${dealer.name}</p>
+                            </div>
+                        </div>
+                        <div class="row mb-3">
+                            <div class="col-md-6">
+                                <p><strong>联系人:</strong>${dealer.contactPerson}</p>
+                            </div>
+                            <div class="col-md-6">
+                                <p><strong>联系方式:</strong>${dealer.contactInfo}</p>
+                            </div>
+                        </div>
+                        <div class="row mb-3">
+                            <div class="col-md-12">
+                                <p><strong>销售地区:</strong>${dealer.salesArea.join('、')}</p>
+                            </div>
+                        </div>
+                        <div class="row mb-3">
+                            <div class="col-md-6">
+                                <p><strong>状态:</strong><span class="${dealer.status == 'normal' ? 'status-normal' : 'status-disabled'}">${dealer.status == 'normal' ? '正常' : '禁用'}</span></p>
+                            </div>
+                        </div>
+                        <div class="row mb-3">
+                            <div class="col-md-6">
+                                <p><strong>创建人:</strong>${dealer.creator}</p>
+                            </div>
+                            <div class="col-md-6">
+                                <p><strong>创建时间:</strong>${dealer.createTime}</p>
+                            </div>
+                        </div>
+                    `;
+                    // 显示模态框
+                    detailModal.show();
+                }
+            }
+
+            // 编辑经销商
+            function editDealer(dealerId) {
+                const dealer = dealerData.find(d => d.id === dealerId);
+                if (dealer) {
+                    $('#dealerId').val(dealer.id);
+                    $('#editDealerCode').val(dealer.id);
+                    $('#editDealerName').val(dealer.name);
+                    $('#editContactPerson').val(dealer.contactPerson);
+                    $('#editContactInfo').val(dealer.contactInfo);
+                    $('#editStatus').prop('checked', dealer.status === 'normal');
+                    $('#statusText').text(dealer.status === 'normal' ? '正常' : '禁用');
+                    selectedAreas = [...dealer.salesArea];
+                    renderSelectedAreas();
+                    $('#editModalLabel').text('编辑经销商');
+                    // 显示模态框
+                    editModal.show();
+                }
+            }
+
+            // 分页按钮点击事件
+            $('.pagination .page-link').on('click', function(e) {
+                e.preventDefault();
+                if (!$(this).parent().hasClass('disabled') && !$(this).parent().hasClass('active')) {
+                    const pageNum = $(this).text();
+                    console.log('跳转到第 ' + pageNum + ' 页');
+                    // 实际应用中,这里应该发送AJAX请求到后端获取对应页码的数据
+                }
+            });
+
+            // 初始化加载数据
+            renderDealerTable(dealerData);
+        });
+    </script>
+</body>
+</html>

+ 302 - 0
src/main/webapp/page/jinzai/factory.jsp

@@ -0,0 +1,302 @@
+<%@ page language="java" contentType="text/html; charset=UTF-8"
+    pageEncoding="UTF-8"%>
+<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
+<c:set value="<%=request.getContextPath()%>" var="ctx"></c:set>
+<!DOCTYPE html>
+<html>
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1.0">
+<title>工厂列表</title>
+<meta name="keywords" content="工厂管理">
+<meta name="description" content="工厂信息管理页面">
+<link href="${ctx}/css/bootstrap.min.css?v=3.3.6" rel="stylesheet">
+<link href="${ctx}/css/font-awesome.css?v=4.4.0" rel="stylesheet">
+<link href="${ctx}/css/bootstrap-select.min.css" rel="stylesheet">
+<link href="${ctx}/css/plugins/bootstrap-table/bootstrap-table.min.css" rel="stylesheet">
+<link href="${ctx}/css/animate.css" rel="stylesheet">
+<link href="${ctx}/css/style.css?v=4.1.0" rel="stylesheet">
+</head>
+
+<body class="gray-bg">
+    <div class="wrapper wrapper-content animated fadeInRight">
+        <div class="row">
+            <div class="col-sm-12">
+                <div class="ibox">
+                    <div class="ibox-title">
+                        <div class="row">
+                            <div class="col-sm-10">
+                                <h3>工厂列表</h3>
+                           </div>
+                        </div>
+                    </div>
+
+                    <div class="ibox-content">
+                     <div class="row row-lg">
+                     <form class="form-horizontal m-t" >
+                <div id="condition" class="form-group" style="margin-bottom: 0;">
+                    <div class="col-sm-3">
+                        <label class="col-sm-4 control-label" style="text-align: right;"><span class="text-danger"></span>工厂名称:</label>
+                        <div class="col-sm-8">
+                            <input id="factoryName" class="form-control" placeholder="请输入工厂名称"/>
+                        </div>
+                    </div>
+                    <div class="col-sm-6">
+                        <button type="button" id="searchBtn" class="btn btn-success" onclick="search();return false;">搜索</button>
+                        <button type="button" id="resetBtn" class="btn btn-default" onclick="reset();return false;">重置</button>
+                        <button type="button" class="btn btn-primary pull-right" onclick="addFactory();">
+                            <i class="glyphicon glyphicon-plus"></i> 添加工厂
+                        </button>
+                    </div>
+                </div>
+                  </form>
+                </div>
+                  <div class="row row-lg">
+                 <div class="col-sm-12">
+                  <table id="table" data-toggle="table"  data-mobile-responsive="true">
+                            </table>
+                </div>
+                 </div>
+
+
+                    </div>
+
+                </div>
+            </div>
+        </div>
+    </div>
+
+    <!-- 全局js -->
+    <script src="${ctx}/js/jquery.min.js?v=2.1.4"></script>
+    <script src="${ctx}/js/bootstrap.min.js?v=3.3.6"></script>
+    <script src="${ctx}/js/bootstrap-select.min.js"></script>
+    <!-- 自定义js -->
+    <script src="${ctx}/js/content.js?v=1.0.0"></script>
+    <!-- jQuery Validation plugin javascript-->
+    <script src="${ctx}/js/plugins/validate/jquery.validate.min.js"></script>
+    <script src="${ctx}/js/plugins/validate/messages_zh.min.js"></script>
+    <script src="${ctx}/js/plugins/bootstrap-table/bootstrap-table.min.js"></script>
+    <script src="${ctx}/js/plugins/bootstrap-table/bootstrap-table-mobile.min.js"></script>
+    <script src="${ctx}/js/plugins/bootstrap-table/locale/bootstrap-table-zh-CN.min.js"></script>
+    <script src="${ctx}/js/common.js"></script>
+    <script src="${ctx}/js/plugins/layer/layer.min.js"></script>
+    <script src="${ctx}/js/Math.uuid.js"></script>
+</body>
+<script>
+var table = null;
+$(document).ready(function(){
+    table = $('#table').bootstrapTable("destroy");
+    initTable();
+});
+
+function queryParams(param){
+    let factoryName = $.trim($("#factoryName").val());
+    if(factoryName){
+        param['factoryName'] = factoryName;
+    }
+    return param;
+}
+
+function search(){
+    table = $('#table').bootstrapTable("destroy");
+    initTable();
+}
+
+function reset(){
+    $("#factoryName").val('');
+    table = $('#table').bootstrapTable("destroy");
+    initTable();
+}
+
+function addFactory() {
+    layer.open({
+        type: 2,
+        title: '新增/编辑工厂',
+        area: ['800px', '600px'],
+        content: '${ctx}/page/jinzai/factory_add.jsp',
+        end: function() {
+            // 修正表格ID,从#factoryTable改为#table
+            $('#table').bootstrapTable('refresh');
+        }
+    });
+}
+
+function editFactory(id) {
+    layer.open({
+        type: 2,
+        title: '编辑工厂',
+        content: '${ctx}/page/jinzai/factory_add.jsp?id=' + id,
+        area: ['800px', '600px'],
+        maxmin: true,
+        end: function() {
+            // 关闭弹窗后刷新表格
+            $('#table').bootstrapTable('refresh');
+        }
+    });
+}
+
+function toggleStatus(id, status){
+    <%--layer.confirm('确定要' + (status == 1 ? '停用' : '启用') + '该工厂吗?', {--%>
+    <%--    btn: ['确定','取消']--%>
+    <%--}, function(){--%>
+    <%--    $.ajax({--%>
+    <%--        url: '${ctx}/factory/toggleStatus',--%>
+    <%--        type: 'post',--%>
+    <%--        data: {--%>
+    <%--            id: id,--%>
+    <%--            status: status == 1 ? 0 : 1--%>
+    <%--        },--%>
+    <%--        success: function(result){--%>
+    <%--            if(result.code == 200){--%>
+    <%--                layer.msg(result.msg, {icon: 1});--%>
+    <%--                search(); // 刷新表格--%>
+    <%--            } else {--%>
+    <%--                layer.msg(result.msg, {icon: 2});--%>
+    <%--            }--%>
+    <%--        },--%>
+    <%--        error: function(){--%>
+    <%--            layer.msg('操作失败', {icon: 2});--%>
+    <%--        }--%>
+    <%--    });--%>
+    <%--});--%>
+}
+
+function initTable(){
+    table = $('#table').bootstrapTable({
+        method: 'get',
+        sortable : true,
+        toolbar: '#toolbar',    //工具按钮用哪个容器
+        striped: true,      //是否显示行间隔色
+        cache: false,      //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*)
+        pagination: true,     //是否显示分页(*)
+        pageNumber: 1,      //初始化加载第一页,默认第一页
+        pageSize: 10,      //每页的记录行数(*)
+        pageList: [10, 25, 50, 100],  //可供选择的每页的行数(*)
+        url: '${ctx}/factory/list',//这个接口需要处理bootstrap table传递的固定参数
+        queryParamsType: '', //默认值为 'limit' ,在默认情况下 传给服务端的参数为:offset,limit,sort
+                            // 设置为 ''  在这种情况下传给服务器的参数为:pageSize,pageNumber
+
+        queryParams: queryParams,//前端调用服务时,会默认传递上边提到的参数,如果需要添加自定义参数,可以自定义一个函数返回请求参数
+        sidePagination: "server",   //分页方式:client客户端分页,server服务端分页(*)
+        strictSearch: false,
+        minimumCountColumns: 2,    //最少允许的列数
+        clickToSelect: true,    //是否启用点击选中行
+        searchOnEnterKey: true,
+        idField : "id",
+        // 设置数据格式转换
+        responseHandler: function(res) {
+            // 这里假设接口返回的data就是我们需要的表格数据
+            return {
+                total: res.total,  // 总记录数
+                rows: res.records  // 数据列表
+            };
+        },
+        columns: [{
+            title: '序号',
+            align: 'center',
+            formatter: function (value, row, index) {
+                // 使用this关键字访问表格实例
+                var pageNumber = this.pageNumber || 1;
+                var pageSize = this.pageSize || 10;
+                return (pageNumber - 1) * pageSize + index + 1;
+            },
+            width: "5%"
+        },{
+            field: 'factoryCode',
+            title: '工厂编号',
+            align: 'center',
+            width: "10%"
+        },{
+            field: 'factoryName',
+            title: '工厂名称',
+            align: 'center',
+            width: "15%"
+        },{
+            field: 'contactPerson',
+            title: '联系人',
+            align: 'center',
+            width: "10%",
+            formatter: function (value) {
+                return value || '-';  // 处理null值
+            }
+        },{
+            field: 'contactPhone',
+            title: '联系方式',
+            align: 'center',
+            width: "10%"
+        },{
+            field: 'provinceCityDistrict',
+            title: '地区',
+            align: 'center',
+            width: "15%"
+        },{
+            field: 'addressDetail',
+            title: '详细地址',
+            align: 'center',
+            width: "15%"
+        },{
+            field: 'status',
+            title: '状态',
+            align: 'center',
+            formatter: function (value) {
+                if (value == 1) {
+                    return '<span class="label label-success">启用</span>';
+                } else {
+                    return '<span class="label label-danger">停用</span>';
+                }
+            },
+            width: "8%"
+        },{
+            title: '操作',
+            align: 'center',
+            width: "12%",
+            formatter: function (value, row) {
+                return '<button class="btn btn-primary btn-xs" onclick="editFactory(' + row.id + ')">编辑</button> ' +
+                       '<button class="btn btn-danger btn-xs" onclick="deleteFactory(' + row.id + ')">删除</button>';
+            }
+        }],
+        onLoadSuccess: function (data) {
+            console.log("数据加载成功", data);
+        },
+        onLoadError: function () {
+            layer.msg('数据加载失败', {icon: 2});
+        }
+    });
+}
+</script>
+<script type="text/javascript">
+
+function isEmpty(obj){
+    if(obj == undefined || obj == null || obj == ''){
+        return true;
+    }else{
+        return false;
+    }
+}
+
+function deleteFactory(id) {
+    layer.confirm('确定要删除该工厂吗?此操作不可撤销!', {
+        btn: ['确定','取消']
+    }, function(){
+        $.ajax({
+            url: '${ctx}/factory/delete',
+            type: 'post',
+            data: {
+                id: id
+            },
+            success: function(result){
+                if(result.code === 0){
+                    layer.msg(result.msg, {icon: 1});
+                    search(); // 刷新表格
+                } else {
+                    layer.msg(result.msg, {icon: 2});
+                }
+            },
+            error: function(){
+                layer.msg('删除失败', {icon: 2});
+            }
+        });
+    });
+}
+</script>
+</html>

+ 492 - 0
src/main/webapp/page/jinzai/factory_add.jsp

@@ -0,0 +1,492 @@
+<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
+<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
+<c:set value="<%=request.getContextPath()%>" var="ctx"></c:set>
+<!DOCTYPE html>
+<html lang="zh-CN">
+<head>
+    <meta charset="UTF-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <title>新增/编辑工厂</title>
+    <!-- 引入Bootstrap CSS -->
+    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
+    <!-- 引入Font Awesome图标 -->
+    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
+    <style>
+        .required::before {
+            content: '*';
+            color: red;
+            margin-right: 5px;
+        }
+
+        .form-group {
+            margin-bottom: 1.5rem; /* 增加字段间距 */
+        }
+
+        .toggle-switch {
+            position: relative;
+            display: inline-block;
+            width: 60px;
+            height: 34px;
+        }
+
+        .toggle-switch input {
+            opacity: 0;
+            width: 0;
+            height: 0;
+        }
+
+        .slider {
+            position: absolute;
+            cursor: pointer;
+            top: 0;
+            left: 0;
+            right: 0;
+            bottom: 0;
+            background-color: #ccc;
+            transition: .4s;
+            border-radius: 34px;
+        }
+
+        .slider:before {
+            position: absolute;
+            content: "";
+            height: 26px;
+            width: 26px;
+            left: 4px;
+            bottom: 4px;
+            background-color: white;
+            transition: .4s;
+            border-radius: 50%;
+        }
+
+        input:checked + .slider {
+            background-color: #2196F3;
+        }
+
+        input:checked + .slider:before {
+            transform: translateX(26px);
+        }
+
+        /* 自定义表单容器样式 */
+        .form-container {
+            padding: 20px;
+            border-radius: 8px;
+            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
+            background-color: #fff;
+        }
+    </style>
+</head>
+<body style="background-color: #f5f7fa; padding: 20px;">
+<div class="form-container">
+    <form id="factoryForm">
+        <div class="row mb-4">
+            <input type="hidden" id="factoryId" name="factoryId">
+            <div class="col">
+                <label for="factoryCode" class="required">工厂编号</label>
+                <input type="text" class="form-control" id="factoryCode" name="factoryCode" placeholder="请输入"
+                       required>
+                <small class="form-text text-muted">工厂编号规则:不超过50个字符</small>
+            </div>
+            <div class="col">
+                <label for="factoryName" class="required">工厂名称</label>
+                <input type="text" class="form-control" id="factoryName" name="factoryName" placeholder="请输入"
+                       required>
+                <small class="form-text text-muted">名称:不超过50个字符</small>
+            </div>
+        </div>
+
+        <div class="row mb-4">
+            <div class="col">
+                <label for="region" class="required">所在地区</label>
+                <div class="row g-3">
+                    <div class="col-sm-4">
+                        <select class="form-select" id="province" name="province" required>
+                            <option value="">请选择省份</option>
+                        </select>
+                    </div>
+                    <div class="col-sm-4">
+                        <select class="form-select" id="city" name="city" disabled required>
+                            <option value="">请选择城市</option>
+                        </select>
+                    </div>
+                    <div class="col-sm-4">
+                        <select class="form-select" id="district" name="district" disabled required>
+                            <option value="">请选择区县</option>
+                        </select>
+                    </div>
+                </div>
+            </div>
+            <div class="col">
+                <label for="factoryAddress">工厂地址</label>
+                <input type="text" class="form-control" id="factoryAddress" name="factoryAddress"
+                       placeholder="请输入">
+            </div>
+        </div>
+
+        <div class="row mb-4">
+            <div class="col">
+                <label for="contactPerson" class="required">联系人</label>
+                <input type="text" class="form-control" id="contactPerson" name="contactPerson" placeholder="请输入"
+                       required>
+            </div>
+            <div class="col">
+                <label for="contactMethod">联系方式</label>
+                <input type="text" class="form-control" id="contactMethod" name="contactMethod" placeholder="请输入">
+            </div>
+        </div>
+
+        <div class="row mb-4">
+            <div class="col">
+                <label for="companyWebsite">企业网址</label>
+                <input type="text" class="form-control" id="companyWebsite" name="companyWebsite" placeholder="请输入">
+            </div>
+            <div class="col">
+                <label for="zipCode">邮政编码</label>
+                <input type="text" class="form-control" id="zipCode" name="zipCode" placeholder="请输入">
+            </div>
+        </div>
+
+        <div class="row mb-4">
+            <div class="col">
+                <label for="afterSalePhone">售后服务电话</label>
+                <input type="text" class="form-control" id="afterSalePhone" name="afterSalePhone" placeholder="请输入">
+            </div>
+            <div class="col">
+                <label for="status" class="required">状态</label>
+                <div class="d-flex align-items-center gap-2">
+                    <label class="toggle-switch">
+                        <input type="checkbox" id="status" name="status" checked>
+                        <span class="slider"></span>
+                    </label>
+                    <span id="statusText">正常</span>
+                    <small class="form-text text-muted">状态:正常、禁用,默认正常</small>
+                </div>
+            </div>
+        </div>
+
+        <div class="row mb-4">
+            <div class="col">
+                <label for="detailedAddress">详细地址</label>
+                <input type="text" class="form-control" id="detailedAddress" name="detailedAddress"
+                       placeholder="请输入">
+            </div>
+        </div>
+
+        <div class="mt-4 d-flex justify-content-end gap-3">
+            <!-- 修改取消按钮的onclick事件 -->
+            <button type="button" class="btn btn-secondary" onclick="parent.layer.closeAll()">取消</button>
+            <button type="submit" class="btn btn-primary">确定</button>
+        </div>
+    </form>
+</div>
+
+<!-- 引入jQuery -->
+<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
+<!-- 引入Bootstrap JS -->
+<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
+<script src="${ctx}/js/plugins/layer/layer.min.js"></script>
+<script src="${ctx}/js/plugins/validate/jquery.validate.min.js"></script>
+<script src="${ctx}/js/plugins/validate/messages_zh.min.js"></script>
+
+<script>
+    // 在页面加载时检查是否有编辑ID
+    $(document).ready(function() {
+        initValidation();
+        loadProvinces();
+    
+        // 获取URL中的ID参数
+        const urlParams = new URLSearchParams(window.location.search);
+        const factoryId = urlParams.get('id');
+        // 如果存在ID,则加载工厂数据
+        if (factoryId) {
+            loadFactoryData(factoryId);
+        }
+    });
+    
+    // 加载工厂数据
+    function loadFactoryData(id) {
+        $.ajax({
+            url: '${ctx}/factory/getById?id=' + id,
+            type: 'GET',
+            dataType: 'json',
+            success: function(data) {
+                if (data.code === 0) {
+                    const factory = data.data;
+                    // 填充表单数据
+                    $('#factoryId').val(factory.id);
+                    $('#factoryCode').val(factory.factoryCode);
+                    $('#factoryName').val(factory.factoryName);
+                    $('#contactPerson').val(factory.contactPerson);
+                    $('#contactMethod').val(factory.contactPhone);
+                    $('#factoryAddress').val(factory.address);
+                    $('#zipCode').val(factory.postalCode);
+                    $('#companyWebsite').val(factory.website);
+                    $('#detailedAddress').val(factory.addressDetail);
+                    $('#afterSalePhone').val(factory.servicePhone);
+    
+                    // 设置状态开关
+                    if (factory.status === 1) {
+                        $('#status').prop('checked', true);
+                    } else {
+                        $('#status').prop('checked', false);
+                    }
+    
+                    // 回显地区信息的改进版本
+                    if (factory.provinceCityDistrict) {
+                        const regionParts = factory.provinceCityDistrict.split('-');
+                        if (regionParts.length === 3) {
+                            const province = regionParts[0];
+                            const city = regionParts[1];
+                            const district = regionParts[2];
+    
+                            // 先选择省份
+                            $('#province').val(province);
+                            // 触发省份change事件,加载城市
+                            $('#province').trigger('change');
+                            
+                            // 使用setTimeout确保城市数据已加载完成
+                            setTimeout(function() {
+                                // 选择城市
+                                $('#city').val(city);
+                                // 触发城市change事件,加载区县
+                                $('#city').trigger('change');
+                                
+                                // 再次使用setTimeout确保区县数据已加载完成
+                                setTimeout(function() {
+                                    // 选择区县
+                                    $('#district').val(district);
+                                }, 300);
+                            }, 300);
+                        }
+                    }
+                } else {
+                    layer.msg(data.msg, {icon: 5});
+                }
+            },
+            error: function() {
+                layer.msg('加载工厂数据失败', {icon: 5});
+            }
+        });
+    }
+    
+    // 修改loadCities函数以支持回显
+    function loadCities(provinceName, selectedCity) {
+        $.getJSON('${ctx}/common/area.json', function(data) {
+            const cities = data[provinceName] || {};
+            const citySelect = $('#city');
+            const districtSelect = $('#district');
+    
+            // 清空城市和区县选择框
+            citySelect.empty().append('<option value="">请选择城市</option>');
+            districtSelect.empty().append('<option value="">请选择区县</option>');
+    
+            // 填充城市
+            for (const city in cities) {
+                const selected = (selectedCity && city === selectedCity) ? 'selected' : '';
+                citySelect.append('<option value="' + city + '" ' + selected + '>' + city + '</option>');
+            }
+    
+            // 如果有选中的城市,加载对应的区县
+            if (selectedCity) {
+                loadDistricts(selectedCity);
+            }
+        });
+    }
+    
+    // 修改loadDistricts函数以支持回显
+    function loadDistricts(cityName, selectedDistrict) {
+        const provinceName = $('#province').val();
+    
+        $.getJSON('${ctx}/common/area.json', function(data) {
+            const cities = data[provinceName] || {};
+            const districts = cities[cityName] || [];
+            const districtSelect = $('#district');
+    
+            // 清空区县选择框
+            districtSelect.empty().append('<option value="">请选择区县</option>');
+    
+            // 填充区县
+            districts.forEach(function(district) {
+                const selected = (selectedDistrict && district === selectedDistrict) ? 'selected' : '';
+                districtSelect.append('<option value="' + district + '" ' + selected + '>' + district + '</option>');
+            });
+        });
+    }
+    
+    // 状态切换按钮
+    const statusToggle = document.getElementById('status');
+    const statusText = document.getElementById('statusText');
+    
+    statusToggle.addEventListener('change', function () {
+        if (this.checked) {
+            statusText.textContent = '正常';
+        } else {
+            statusText.textContent = '禁用';
+        }
+    });
+    
+    // 表单验证
+    // document.getElementById('factoryForm').addEventListener('submit', function (event) {
+    //     event.preventDefault();
+    //     saveFactory();
+    // });
+    
+    // 加载省份数据
+    function loadProvinces() {
+        $.getJSON('${ctx}/common/area.json', function (data) {
+            const provinceSelect = $('#province');
+            provinceSelect.empty().append('<option value="">请选择省份</option>');
+    
+            $.each(data, function (provinceName, cities) {
+                provinceSelect.append('<option value="' + provinceName + '">' + provinceName + '</option>');
+            });
+    
+            // 绑定省份选择事件
+            provinceSelect.on('change', function () {
+                const selectedProvince = $(this).val();
+                if (selectedProvince) {
+                    loadCities(selectedProvince, data);
+                } else {
+                    $('#city').empty().append('<option value="">请选择城市</option>').prop('disabled', true);
+                    $('#district').empty().append('<option value="">请选择区县</option>').prop('disabled', true);
+                }
+            });
+        });
+    }
+    
+    // 加载城市数据
+    function loadCities(province, data) {
+        const citySelect = $('#city');
+        citySelect.empty().append('<option value="">请选择城市</option>').prop('disabled', false);
+        $('#district').empty().append('<option value="">请选择区县</option>').prop('disabled', true);
+    
+        const cities = data[province];
+        $.each(cities, function (cityName, districts) {
+            citySelect.append('<option value="' + cityName + '">' + cityName + '</option>');
+        });
+    
+        // 绑定城市选择事件
+        citySelect.on('change', function () {
+            const selectedCity = $(this).val();
+            if (selectedCity) {
+                loadDistricts(province, selectedCity, data);
+            } else {
+                $('#district').empty().append('<option value="">请选择区县</option>').prop('disabled', true);
+            }
+        });
+    }
+    
+    // 加载区县数据
+    function loadDistricts(province, city, data) {
+        const districtSelect = $('#district');
+        districtSelect.empty().append('<option value="">请选择区县</option>').prop('disabled', false);
+    
+        const districts = data[province][city];
+        $.each(districts, function (index, districtName) {
+            districtSelect.append('<option value="' + districtName + '">' + districtName + '</option>');
+        });
+    }
+    
+    // 保存工厂信息
+    function saveFactory() {
+        // 获取表单数据
+        const id = $('#factoryId').val();
+        const formData = {
+            id: id,
+            factoryCode: $('#factoryCode').val(),
+            factoryName: $('#factoryName').val(),
+            provinceCityDistrict: $('#province').val() + '-' + $('#city').val() + '-' + $('#district').val(),
+            contactPerson: $('#contactPerson').val(),
+            contactPhone: $('#contactMethod').val(),
+            address: $('#factoryAddress').val(),
+            postalCode: $('#zipCode').val(),
+            website: $('#companyWebsite').val(),
+            addressDetail: $('#detailedAddress').val(),
+            status: $('#status').is(':checked') ? 1 : 0,
+            servicePhone: $('#afterSalePhone').val()
+        };
+
+        $.ajax({
+            url: id != null ? '${ctx}/factory/update' :'${ctx}/factory/save',
+            type: 'POST',
+            data: JSON.stringify(formData),
+            contentType: 'application/json',
+            success: function(data) {
+                if (data.code === 0) {
+                    layer.msg('保存成功', {icon: 6});
+                    // 关闭弹窗
+                    parent.layer.closeAll();
+                } else {
+                    layer.msg(data.msg, {icon: 5});
+                }
+            },
+            error: function() {
+                layer.msg('保存失败', {icon: 5});
+            }
+        });
+    }
+
+    function initValidation() {
+        $('#factoryForm').validate({
+            rules: {
+                factoryCode: {
+                    required: true,
+                    maxlength: 20
+                },
+                factoryName: {
+                    required: true,
+                    maxlength: 100
+                },
+                province: {
+                    required: true
+                },
+                city: {
+                    required: true
+                },
+                contactPerson: {
+                    required: true,
+                    maxlength: 20
+                },
+                contactPhone: {
+                    required: true,
+                    isPhone: true
+                },
+                email: {
+                    email: true
+                }
+            },
+            messages: {
+                factoryCode: {
+                    required: '请输入工厂编号',
+                    maxlength: '工厂编号最多20个字符'
+                },
+                factoryName: {
+                    required: '请输入工厂名称',
+                    maxlength: '工厂名称最多100个字符'
+                },
+                province: {
+                    required: '请选择省份'
+                },
+                city: {
+                    required: '请选择城市'
+                },
+                contactPerson: {
+                    required: '请输入联系人',
+                    maxlength: '联系人最多20个字符'
+                },
+                contactPhone: {
+                    required: '请输入联系电话',
+                    isPhone: '请输入有效的联系电话'
+                },
+                email: {
+                    email: '请输入有效的电子邮箱'
+                }
+            },
+            submitHandler: function(form) {
+                saveFactory();
+            }
+        });
+    }
+</script>
+</body>
+</html>