# -*- coding: utf-8 -*-
"""导入销售订单示例数据。用法: python Install/load_sale_sample.py"""
import os
import sys
import datetime

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if BASE_DIR not in sys.path:
    sys.path.insert(0, BASE_DIR)

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mis.settings')

import django
django.setup()

from decimal import Decimal
from django.contrib.auth.models import User
from django.db import transaction
from basedata.models import Partner, Material, Organization
from sale.models import SaleOrder, SaleItem


def recalc_order_amount(order):
    total = Decimal('0')
    for item in SaleItem.objects.filter(master=order):
        price = item.sale_price or Decimal('0')
        total += price * item.cnt
    SaleOrder.objects.filter(pk=order.pk).update(amount=total)
    order.amount = total
    return total


SAMPLE_ORDERS = [
    {
        'code': 'SO00001',
        'title': u'办公设备采购订单',
        'order_date': datetime.date(2025, 5, 10),
        'deliver_date': datetime.date(2025, 5, 25),
        'contact': u'张经理',
        'phone': '13800138001',
        'deliver_address': u'上海市浦东新区张江高科技园区科苑路88号',
        'description': u'含笔记本电脑及服务器，需上门安装调试。',
        'status': '9',
        'discount_amount': 0,
        'items': [
            {'material_code': 'IT5001', 'cnt': 2, 'sale_price': 7150.00},
            {'material_code': 'IT5002', 'cnt': 1, 'sale_price': 9999.00},
        ],
    },
    {
        'code': 'SO00002',
        'title': u'配电设备批量采购',
        'order_date': datetime.date(2025, 5, 15),
        'deliver_date': datetime.date(2025, 6, 1),
        'contact': u'李工',
        'phone': '13900139002',
        'deliver_address': u'江苏省南京市江宁区将军大道29号',
        'description': u'项目现场配电改造用材。',
        'status': '1',
        'discount_amount': 200.00,
        'items': [
            {'material_code': 'IT9981', 'cnt': 20, 'sale_price': 320.00},
        ],
    },
    {
        'code': 'SO00003',
        'title': u'水果批发季节订单',
        'order_date': datetime.date(2025, 5, 18),
        'deliver_date': datetime.date(2025, 5, 22),
        'contact': u'王采购',
        'phone': '13700137003',
        'deliver_address': u'浙江省杭州市余杭区良渚街道物流园A区',
        'description': u'当季鲜果直采，分批配送。',
        'status': '0',
        'discount_amount': 0,
        'items': [
            {'material_code': 'IT9001', 'cnt': 500, 'sale_price': 11.00},
            {'material_code': 'IT9002', 'cnt': 300, 'sale_price': 16.00},
            {'material_code': 'IT9003', 'cnt': 200, 'sale_price': 19.00},
        ],
    },
    {
        'code': 'SO00004',
        'title': u'劳保用品集中采购',
        'order_date': datetime.date(2025, 5, 20),
        'deliver_date': datetime.date(2025, 5, 28),
        'contact': u'赵主任',
        'phone': '13600136004',
        'deliver_address': u'安徽省合肥市蜀山区望江西路666号',
        'description': u'车间一线员工劳保手套补充采购。',
        'status': '9',
        'discount_amount': 0,
        'items': [
            {'material_code': 'IT00005', 'cnt': 1000, 'sale_price': 5.50},
        ],
    },
]


def load_samples():
    partner = Partner.objects.filter(partner_type='C').first()
    if not partner:
        print(u'错误: 未找到客户类型合作伙伴，请先维护基础数据。')
        return

    user = User.objects.filter(username='chengcai').first() or User.objects.first()
    org = Organization.objects.first()
    creator = user.username if user else 'system'
    today = datetime.date.today()

    created = 0
    skipped = 0

    with transaction.atomic():
        for data in SAMPLE_ORDERS:
            if SaleOrder.objects.filter(code=data['code']).exists():
                print(u'跳过已存在订单: %s' % data['code'])
                skipped += 1
                continue

            order = SaleOrder(
                code=data['code'],
                title=data['title'],
                order_date=data['order_date'],
                deliver_date=data['deliver_date'],
                partner=partner,
                org=org,
                user=user,
                contact=data['contact'],
                phone=data['phone'],
                deliver_address=data['deliver_address'],
                description=data['description'],
                invoice_type='10',
                status=data['status'],
                discount_amount=data['discount_amount'],
                amount=0,
                begin=today,
                end=datetime.date(9999, 12, 31),
                creator=creator,
                modifier=creator,
            )
            order.save()

            for item_data in data['items']:
                material = Material.objects.filter(code=item_data['material_code']).first()
                if not material:
                    print(u'警告: 物料 %s 不存在，已跳过' % item_data['material_code'])
                    continue
                item = SaleItem(
                    master=order,
                    material=material,
                    cnt=item_data['cnt'],
                    sale_price=item_data['sale_price'],
                    tax='0.00',
                )
                item.save()

            if data['discount_amount'] > 0:
                order.save()
            total = recalc_order_amount(order)
            print(u'已创建: %s %s  金额=%s  状态=%s' % (
                order.code, order.title, total, order.get_status_display()
            ))
            created += 1

    print(u'\n完成: 新增 %d 条，跳过 %d 条。' % (created, skipped))


if __name__ == '__main__':
    load_samples()
