'use strict';
const moment = require('moment')

async function bindAnxin2pep (ctx) {
   const transaction = await ctx.fs.dc.orm.transaction();
   try {
      const models = ctx.fs.dc.models;
      const { clickHouse } = ctx.app.fs
      const { userId, pepUserId } = ctx.fs.api
      const { bindId, name, pepProjectId, anxinProjectId = [], appId = [], mappingClass } = ctx.request.body

      if (name && pepProjectId) {
         throw '项企项目与自定义项目名称仅可选择一项'
      }

      let bindId_ = bindId
      const now = moment()

      let storageData = {
         name, pepProjectId, anxinProjectId,
         updateTime: now, mappingClass,
         del: false,
      }

      // 仅限已有 pepProjectId 的项目
      const existRes = pepProjectId ? await models.ProjectCorrelation.findOne({
         where: Object.assign(
            {},
            pepProjectId ? {
               pepProjectId: pepProjectId
            } : {
               name,
            }
         ),
      }) : null

      if (name) {
         const pepRepeatNameCount = await clickHouse.projectManage.query(`SELECT COUNT(*) AS count FROM t_pim_project WHERE project_name='${name}'`).toPromise()
         if (pepRepeatNameCount[0].count) {
            throw `已有相同名称【${name}】的项企项目`
         }
         const pomsRepeatNameRes = await models.ProjectCorrelation.findAll({
            where: {
               name
            }
         })
         if (pomsRepeatNameRes.some((pr) => {
            return (
               (
                  // 有修改id但是不等于当前修改id的
                  bindId && pr.id != bindId && !pr.del
               ) || (
                  !bindId && (
                     (
                        existRes && pr.id != existRes.id && !pr.del
                     ) || (
                        !existRes && !pr.del
                     )
                  )
               )
            )
         })) {
            throw `已有相同名称【${name}】的自定义项目`
         }
      } else {
         const pomsRepeatProjectIdRes = await models.ProjectCorrelation.findAll({
            where: {
               pepProjectId: pepProjectId
            }
         })
         if (pomsRepeatProjectIdRes.some((pr) => {
            return (
               (
                  // 有修改id但是不等于当前修改id的
                  bindId && pr.id != bindId && !pr.del
               ) || (
                  !bindId && (
                     (
                        existRes && pr.id != existRes.id && !pr.del
                     ) || (
                        !existRes && !pr.del
                     )
                  )
               )
            )
         })) {
            throw `当前项企项目已绑定`
         }
         storageData.name = null
      }



      if (bindId) {
         // 修改
         await models.ProjectCorrelation.update(storageData, {
            where: {
               id: bindId
            },
            transaction
         })
      } else {
         // 新增
         if (existRes) {
            // 但是有之前的数据
            if (existRes.del) {
               // 不过之前的删除了
               storageData.createUser = userId
               storageData.updateTime = now.format()
               storageData.createTime = now.format()
               await models.ProjectCorrelation.update(storageData, {
                  where: {
                     pepProjectId: pepProjectId
                  },
                  transaction
               })
               bindId_ = existRes.id
            } else {
               // 没有删除 重复添加
               throw '当前项企项目已绑定'
            }
         } else {
            storageData.createUser = userId;
            storageData.createTime = now.format()
            const createRes = await models.ProjectCorrelation.create(storageData, {
               transaction
            })
            bindId_ = createRes.id
         }
      }

      if (bindId) {
         await models.ProjectApp.destroy({
            where: {
               projectId: bindId
            },
            transaction
         })
      }
      await models.ProjectApp.bulkCreate(appId.map(aid => {
         return {
            projectId: bindId_,
            appId: aid
         }
      }), {
         transaction
      })


      await transaction.commit();
      ctx.status = 204;
   } catch (error) {
      await transaction.rollback();
      ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
      ctx.status = 400;
      ctx.body = {
         message: typeof error == 'string' ? error : undefined
      }
   }
}

async function del (ctx) {
   try {
      const models = ctx.fs.dc.models;
      const { bindId } = ctx.params

      await models.ProjectCorrelation.update({
         del: true
      }, {
         where: {
            id: { $in: bindId.split(',') }
         }
      })

      ctx.status = 204;
   } catch (error) {
      ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
      ctx.status = 400;
      ctx.body = {
         message: typeof error == 'string' ? error : undefined
      }
   }
}


module.exports = {
   bindAnxin2pep,
   del
};