-- MES 设备台账：字典 + 建表 + 设备管理目录菜单 + 设备台账菜单 + 按钮 + 租户 admin 授权（可整文件一次执行）
-- 权限前缀：mes:mes_xsl_equipment_ledger:*
-- 父菜单：设备管理（目录，与 MES基础资料 同级，非 MES管理 子级）；子菜单：设备台账
-- 修改租户：改 SET @mes_tenant_id；新环境也可依赖 Flyway V3.9.2_72__mes_xsl_equipment_ledger.sql
SET NAMES utf8mb4;

INSERT INTO `sys_dict` (`id`, `dict_name`, `dict_code`, `description`, `del_flag`, `create_by`, `create_time`, `type`, `tenant_id`)
SELECT REPLACE(UUID(), '-', ''), 'MES设备台账状态', 'xslmes_equipment_ledger_status', '在用/停用/报废', 0, 'admin', NOW(), 0, 0
WHERE NOT EXISTS (SELECT 1 FROM `sys_dict` WHERE `dict_code` = 'xslmes_equipment_ledger_status' AND `del_flag` = 0);

INSERT INTO `sys_dict_item` (`id`, `dict_id`, `item_text`, `item_value`, `sort_order`, `status`, `create_by`, `create_time`)
SELECT REPLACE(UUID(), '-', ''), d.id, '在用', '0', 1, 1, 'admin', NOW() FROM `sys_dict` d
WHERE d.`dict_code` = 'xslmes_equipment_ledger_status' AND NOT EXISTS (SELECT 1 FROM `sys_dict_item` i WHERE i.`dict_id` = d.id AND i.`item_value` = '0');
INSERT INTO `sys_dict_item` (`id`, `dict_id`, `item_text`, `item_value`, `sort_order`, `status`, `create_by`, `create_time`)
SELECT REPLACE(UUID(), '-', ''), d.id, '停用', '1', 2, 1, 'admin', NOW() FROM `sys_dict` d
WHERE d.`dict_code` = 'xslmes_equipment_ledger_status' AND NOT EXISTS (SELECT 1 FROM `sys_dict_item` i WHERE i.`dict_id` = d.id AND i.`item_value` = '1');
INSERT INTO `sys_dict_item` (`id`, `dict_id`, `item_text`, `item_value`, `sort_order`, `status`, `create_by`, `create_time`)
SELECT REPLACE(UUID(), '-', ''), d.id, '报废', '2', 3, 1, 'admin', NOW() FROM `sys_dict` d
WHERE d.`dict_code` = 'xslmes_equipment_ledger_status' AND NOT EXISTS (SELECT 1 FROM `sys_dict_item` i WHERE i.`dict_id` = d.id AND i.`item_value` = '2');

CREATE TABLE IF NOT EXISTS `mes_xsl_equipment_ledger` (
  `id` varchar(32) NOT NULL COMMENT '主键',
  `process_operation_id` varchar(32) NOT NULL COMMENT '所属工序 mes_xsl_process_operation.id',
  `process_operation_name` varchar(500) DEFAULT NULL COMMENT '工序名称冗余',
  `equipment_name` varchar(500) NOT NULL COMMENT '设备名称（同租户未删除唯一）',
  `ledger_no` varchar(16) DEFAULT NULL COMMENT '编号（租户内从001递增自动生成，只读）',
  `equipment_code` varchar(128) NOT NULL COMMENT '设备编号（同租户未删除唯一）',
  `manufacturer_id` varchar(32) DEFAULT NULL COMMENT '所属设备厂家 mes_xsl_manufacturer.id',
  `manufacturer_name` varchar(500) DEFAULT NULL COMMENT '设备厂家名称冗余',
  `equipment_category_id` varchar(32) DEFAULT NULL COMMENT '设备类别 mes_xsl_equipment_category.id',
  `equipment_category_name` varchar(500) DEFAULT NULL COMMENT '设备类别名称冗余',
  `equipment_type_id` varchar(32) DEFAULT NULL COMMENT '设备类型 mes_xsl_equipment_type.id',
  `equipment_type_name` varchar(500) DEFAULT NULL COMMENT '设备类型名称冗余',
  `factory_id` varchar(32) DEFAULT NULL COMMENT '所属工厂（厂家信息）',
  `factory_name` varchar(500) DEFAULT NULL COMMENT '所属工厂名称冗余',
  `equipment_model` varchar(500) DEFAULT NULL COMMENT '设备型号',
  `equipment_status` varchar(1) NOT NULL DEFAULT '0' COMMENT '设备状态 字典xslmes_equipment_ledger_status：0在用1停用2报废',
  `serial_no` varchar(500) DEFAULT NULL COMMENT '序列号',
  `nameplate` varchar(500) DEFAULT NULL COMMENT '铭牌',
  `maintain_dept_id` varchar(32) DEFAULT NULL COMMENT '维修部门 sys_depart.id',
  `maintain_person` varchar(500) DEFAULT NULL COMMENT '维修人员',
  `manage_dept_id` varchar(32) DEFAULT NULL COMMENT '主管部门 sys_depart.id',
  `doc_file_no` varchar(500) DEFAULT NULL COMMENT '资料文件编号',
  `production_date` date DEFAULT NULL COMMENT '生产日期',
  `purchase_date` date DEFAULT NULL COMMENT '购买日期',
  `use_date` date DEFAULT NULL COMMENT '使用日期',
  `vendor_contact` varchar(500) DEFAULT NULL COMMENT '厂商联系人',
  `asset_value` varchar(128) DEFAULT NULL COMMENT '价值',
  `controlled_pda` varchar(500) DEFAULT NULL COMMENT '受控PDA',
  `overproduction_ratio` varchar(128) DEFAULT NULL COMMENT '超产比率',
  `effective_volume` varchar(128) DEFAULT NULL COMMENT '有效体积',
  `enabled_flag` varchar(1) NOT NULL DEFAULT '1' COMMENT '是否启用 字典yn：1是0否',
  `equipment_desc` varchar(1000) DEFAULT NULL COMMENT '设备描述',
  `tenant_id` int DEFAULT NULL COMMENT '租户',
  `sys_org_code` varchar(500) DEFAULT NULL COMMENT '部门',
  `create_by` varchar(500) DEFAULT NULL COMMENT '创建人',
  `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  `update_by` varchar(500) DEFAULT NULL COMMENT '更新人',
  `update_time` datetime DEFAULT NULL COMMENT '更新时间',
  `del_flag` int DEFAULT '0' COMMENT '删除标记（0正常1删除）',
  PRIMARY KEY (`id`),
  KEY `idx_mel_tenant_code` (`tenant_id`, `equipment_code`),
  KEY `idx_mel_tenant_ledger_no` (`tenant_id`, `ledger_no`),
  KEY `idx_mel_tenant_name` (`tenant_id`, `equipment_name`),
  KEY `idx_mel_process` (`process_operation_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='MES设备台账';

SET @mes_tenant_id = 1002;

-- 与「MES基础资料」同级：取其 parent_id（通常为 NULL，与 MES管理 并列）
SET @mes_equip_root_parent = (
  SELECT `parent_id` FROM `sys_permission`
  WHERE `del_flag` = 0 AND `menu_type` = 0 AND `name` = 'MES基础资料'
  LIMIT 1
);
SET @mes_equip_root_parent = IFNULL(@mes_equip_root_parent, (
  SELECT `parent_id` FROM `sys_permission`
  WHERE `del_flag` = 0 AND `menu_type` = 0 AND `name` = 'MES资料'
  LIMIT 1
));

SET @mes_equip_root_sort = IFNULL((
  SELECT `sort_no` + 1 FROM `sys_permission`
  WHERE `del_flag` = 0 AND `menu_type` = 0 AND `name` IN ('MES基础资料', 'MES资料')
  ORDER BY `sort_no` DESC
  LIMIT 1
), 51);

UPDATE `sys_permission`
SET `is_leaf` = 0
WHERE `id` = '1860000000000000133' AND `del_flag` = 0;

INSERT INTO `sys_permission`(`id`, `parent_id`, `name`, `url`, `component`, `component_name`, `menu_type`, `perms`, `perms_type`, `sort_no`, `is_route`, `is_leaf`, `hidden`, `status`, `del_flag`, `keep_alive`, `internal_or_external`, `create_by`, `create_time`)
VALUES ('1860000000000000133', @mes_equip_root_parent, '设备管理', '/xslmes/equipment', 'layouts/RouteView', 'MesEquipmentLayout', 0, NULL, '1', @mes_equip_root_sort, 1, 0, 0, '1', 0, 0, 0, 'admin', NOW())
ON DUPLICATE KEY UPDATE
`parent_id` = VALUES(`parent_id`), `name` = VALUES(`name`), `url` = VALUES(`url`), `component` = VALUES(`component`),
`menu_type` = VALUES(`menu_type`), `icon` = 'ant-design:tool-outlined', `is_leaf` = 0, `hidden` = 0, `status` = '1', `del_flag` = 0;

UPDATE `sys_permission` SET `icon` = 'ant-design:tool-outlined' WHERE `id` = '1860000000000000133' AND `del_flag` = 0;

INSERT INTO `sys_permission`(`id`, `parent_id`, `name`, `url`, `component`, `component_name`, `menu_type`, `perms`, `perms_type`, `sort_no`, `is_route`, `is_leaf`, `hidden`, `status`, `del_flag`, `keep_alive`, `internal_or_external`, `create_by`, `create_time`)
VALUES ('1860000000000000134', '1860000000000000133', '设备台账', '/xslmes/mesXslEquipmentLedger', 'xslmes/mesXslEquipmentLedger/MesXslEquipmentLedgerList', 'MesXslEquipmentLedgerList', 1, NULL, '1', 1, 1, 0, 0, '1', 0, 1, 0, 'admin', NOW())
ON DUPLICATE KEY UPDATE
`parent_id` = VALUES(`parent_id`), `name` = VALUES(`name`), `url` = VALUES(`url`), `component` = VALUES(`component`), `component_name` = VALUES(`component_name`),
`is_leaf` = 0, `hidden` = 0, `status` = '1', `del_flag` = 0;

INSERT INTO `sys_permission`(`id`, `parent_id`, `name`, `menu_type`, `perms`, `perms_type`, `status`, `del_flag`, `create_by`, `create_time`) VALUES
('1860000000000000135', '1860000000000000134', '新增', 2, 'mes:mes_xsl_equipment_ledger:add', '1', '1', 0, 'admin', NOW()),
('1860000000000000136', '1860000000000000134', '编辑', 2, 'mes:mes_xsl_equipment_ledger:edit', '1', '1', 0, 'admin', NOW()),
('1860000000000000137', '1860000000000000134', '删除', 2, 'mes:mes_xsl_equipment_ledger:delete', '1', '1', 0, 'admin', NOW()),
('1860000000000000138', '1860000000000000134', '批量删除', 2, 'mes:mes_xsl_equipment_ledger:deleteBatch', '1', '1', 0, 'admin', NOW()),
('1860000000000000139', '1860000000000000134', '导出', 2, 'mes:mes_xsl_equipment_ledger:exportXls', '1', '1', 0, 'admin', NOW()),
('1860000000000000140', '1860000000000000134', '导入', 2, 'mes:mes_xsl_equipment_ledger:importExcel', '1', '1', 0, 'admin', NOW())
ON DUPLICATE KEY UPDATE
`parent_id` = VALUES(`parent_id`), `name` = VALUES(`name`), `menu_type` = VALUES(`menu_type`), `perms` = VALUES(`perms`),
`status` = VALUES(`status`), `del_flag` = VALUES(`del_flag`);

INSERT INTO `sys_role_permission`(`id`, `role_id`, `permission_id`, `operate_date`, `operate_ip`)
SELECT REPLACE(UUID(), '-', ''), r.`id`, p.`id`, NOW(), '127.0.0.1'
FROM `sys_role` r
CROSS JOIN `sys_permission` p
WHERE r.`tenant_id` = @mes_tenant_id
  AND r.`role_code` = 'admin'
  AND p.`id` IN (
    '1860000000000000133',
    '1860000000000000134',
    '1860000000000000135', '1860000000000000136', '1860000000000000137', '1860000000000000138',
    '1860000000000000139', '1860000000000000140'
  )
  AND NOT EXISTS (
    SELECT 1 FROM `sys_role_permission` rp
    WHERE rp.`role_id` = r.`id` AND rp.`permission_id` = p.`id`
  );
