# -*- coding: utf-8 -*-
import logging

import pymysql
from scrapy.conf import settings


# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html


class FspiderPipeline(object):
    def process_item(self, item, spider):
        return item


class MariadbPipeline(object):
    @staticmethod
    def process_item(item, spider):
        logger = logging.getLogger(__name__)

        host = settings['DB_HOST']
        port = settings['DB_PORT']
        db = settings['DB_NAME']
        user = settings['DB_USER']
        password = settings['DB_PASSWORD']
        charset = settings['DB_CHARSET']

        conn = pymysql.connect(host=host, port=port, user=user, passwd=password, db=db, charset=charset)
        try:
            cursor = conn.cursor()

            # 处理品牌
            

            # 处理一级分类

            # 处理二级分类

            # 处理三级分类

            # 判断是否已经抓取
            sql = 'select count(*) from item where item_id=%s'
            param = (item['item_id'])
            cursor.execute(sql, param)
            result = cursor.fetchone()
            if result[0] == 0:
                sql = 'insert into item(item_id, item_name, item_price, item_url) values(%s, %s, %s, %s)'
                param = (item['item_id'], item['item_name'], item['item_price'], item['item_url'])
            else:
                sql = 'update item set item_name=%s, item_price=%s, item_url=%s where item_id=%s'
                param = (item['item_name'], item['item_price'], item['item_url'], item['item_id'])
            cursor.execute(sql, param)
            conn.commit()
        except Exception as e:
            conn.rollback()
            logger.error(e)
        finally:
            cursor.close()
            conn.close()

        return item
