<template>
  <div class="container">
    <el-row :gutter="20">
      <el-col :span="16">
        <el-card class="robot-card">
          <!-- <div class="unrobot-box" v-if="!robotInfo.id">

            <el-icon>
              <svg class="icon" aria-hidden="true">
                <use xlink:href="#icon-ai-01"></use>
              </svg>
            </el-icon>
            <el-button ref="ref1" type="primary" icon="Plus" @click="toRobot"> 立即添加机器人 </el-button>

          </div> -->

          <div class="robot-box">
            <el-image class="robot-head" :src="robotInfo.head_url"></el-image>

            <div class="robot-info">
              <p class="robot-name">{{ robotInfo.name }}</p>
              <p class="wx-name">微信：{{ robotInfo.wx_name }}</p>
              <p class="robot-id">服务：{{ robotInfo.server_ip }}</p>
            </div>
            <div class="robot-obj">
              <div class="obj-flex">
                <div class="obj-item">
                  <label>群组</label>
                  <br>
                  <span @click="toPath('/groups')">{{ robotInfo.group_counts }}</span>
                </div>
                <div class="obj-item">
                  <label>外部联系人</label>
                  <br>
                  <span @click="toPath('/user')">{{ robotInfo.external_contact_counts }}</span>
                </div>
              </div>
              <div class="obj-reply" @click="dialogWelcome = true">
                <el-icon>
                  <Edit />
                </el-icon> 通过好友验证回复语
              </div>

            </div>
          </div>

        </el-card>

      </el-col>
      <el-col :span="8">
        <el-card class="" style="height: 140px; position: relative;">
          <div class="title">智能体</div>
          <div class="agent-no" v-if="!agentInfo.agent_id && !skeleton">
            <el-button icon="Plus" type="primary" @click="checkAgent">添加智能体</el-button>
          </div>
          <template v-if="agentInfo.agent_id && !skeleton">

            <div class="agent-info">
              <el-image v-if="agentInfo.agent_type == 1" :src="dify"></el-image>
              <el-image v-if="agentInfo.agent_type == 2" :src="coze"></el-image>
              <div class="robot-icon" v-if="agentInfo.agent_type == 3"><span>FastGPT</span></div>
              <div class="agent-box">
                <p style="margin-top: 2px;" class="name">{{ agentInfo.agent_name }}</p>
                <p style="margin-top: 2px;font-size: 12px;">工作时间：{{ agentInfo.effect_start_time }} ~ {{
                  agentInfo.effect_end_time }} <span
                    v-if="compareTimes(agentInfo.effect_end_time, agentInfo.effect_start_time) == -1">(次日)</span></p>
              </div>

            </div>
            <p class="description">描述：{{ agentInfo.agent_description }}</p>
            <div class="setting">
              <el-icon @click="handleSetting">
                <Setting />
              </el-icon>
              <br />
              <span v-if="agentInfo.status == 1" class="enable">启用中</span>
              <span v-if="agentInfo.status == 2" class="disable">已禁用</span>
              <br />
              <span class="delete" @click="deleteAi">删除</span>
            </div>

          </template>
          <el-skeleton style="margin-top: 7px;" v-if="skeleton" :rows="2" animated />
        </el-card>
      </el-col>
      <el-col :span="24">
        <el-card class="robot-log">
          <label class="title-label">机器人日志</label>
          <!-- <el-icon class="refresh" :class="{ loadingIcon: isRefresh }" @click="handleRefresh">
            <Refresh />
          </el-icon>
          <ul v-if="!isRefresh" v-infinite-scroll="load" class="infinite-list" style="overflow: auto">
            <li v-for="item in logList" :key="item.id" class="infinite-list-item"><span class="remark">{{ item.remark
                }}</span></li>
          </ul>
          <el-skeleton v-if="isRefresh" :rows="5" animated style="margin-top: 20px;" /> -->
          <div style="margin-top: 20px;">
            <el-date-picker v-model="month" type="month" placeholder="选择月份" @change="handleReMonth" format="YYYY-MM"
              value-format="YYYY-MM" :disabled-date="disabledDate" :clearable="false" />
            <el-button type="primary" icon="Search" style="margin-left: 12px;" @click="search">查询</el-button>
            <el-button type="primary" style="margin-left: 12px;float: right;" @click="setKeys">意图关键字</el-button>
          </div>
          <div class="table-box" style="height: calc(100vh - 430px); margin-top: 5px;">
            <el-table :data="logList" style="width: 100%" max-height="calc(100vh - 430px)">
              <template #empty>
                <span v-if="tableLoading">加载中...</span>
                <span v-if="!tableLoading">暂无数据</span>
              </template>
              <el-table-column prop="send_time" label="发送时间" align="center" width="160">
              </el-table-column>
              <el-table-column prop="sender_name" label="发送人昵称" align="center" header-align="center" />
              <el-table-column prop="sender_id" label="发送人ID" align="center" header-align="center" />
              <el-table-column prop="receiver_id" label="接收人ID" align="center" header-align="center" />
              <el-table-column prop="is_room" label="是否是群组消息" align="center" header-align="center">
                <template #default="scope">
                  <span v-if="scope.row.is_room == 1">
                    是
                    <!-- <el-icon>
                      <svg class="icon" aria-hidden="true">
                        <use xlink:href="#icon-xiangqingye-43"></use>
                      </svg>
                    </el-icon> -->
                    <br />
                    {{ scope.row.room_id }}
                  </span>
                  <span v-else>否</span>
                </template>
              </el-table-column>
              <!-- <el-table-column prop="" label="消息内容" align="center" header-align="center">
                <template #default="scope">
                  
                  <el-link :underline="false" type="primary">展开</el-link>
                </template>
              </el-table-column> -->
              <el-table-column label="查看详情" type="expand" width="80" align="center">
                <template #default="scope">
                  <div class="message-box">
                    <json-viewer :expand-depth="3" theme="my-json-theme" :value="scope.row.content"></json-viewer>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="pagination-box">
            <el-pagination v-model:current-page="logQuery.page" v-model:page-size="logQuery.page_size"
              :page-sizes="[10, 20, 30, 40, 50]" :size="logQuery.page_size" background
              layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
              @current-change="handleCurrentChange" />
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-tour v-model="open" content-style="width: 200px;text-align: center;">
      <el-tour-step :target="ref1?.$el" title="">
        <span>点击添加机器人</span>
      </el-tour-step>
    </el-tour>
    <el-dialog v-model="dialogWelcome" title="配置通过好友验证回复语" width="800px" align-center destroy-on-close>
      <div class="dialog-box">
        <Welcome :robotInfo="robotInfo" :welcomeType="'1'" @hideWelcome="hideWelcome" />
      </div>

    </el-dialog>
    <el-dialog v-model="dialogKeywords" title="意图识别" width="800px" align-center destroy-on-close>
      <div class="dialog-box">
        <KeyWords :keywordInfo="keywordInfo" @hideKey="hideKey" />
      </div>

    </el-dialog>

    <el-dialog v-model="dialogKeys" title="查看意图识别列表" width="1000px" align-center :before-close="handleClose">
      <div class="dialog-box">
        <el-input v-model="keyQuery.keyword" style="width: 230px;" placeholder="输入关键字">
          <template #append>
            <el-button icon="Search" @click="searchKeys" />
          </template>
        </el-input>
        <el-button type="primary" icon="Plus" @click="addKey" style="margin-left: 12px;">添加关键字</el-button>
        <el-table :data="keyWordList" style="width: 100%; margin-top: 20px;" max-height="500px">
          <template #empty>
            <span v-if="tableLoading2">加载中...</span>
            <span v-if="!tableLoading2">暂无数据</span>
          </template>
          <el-table-column prop="keyword" label="意图关键字" align="left" width="150" />
          <el-table-column prop="material_type_count" label="素材类型数量" align="center">
          </el-table-column>
          <el-table-column prop="" label="操作" width="100" align="center">
            <template #default="scoped">
              <div class="mht-operations">
                <el-tooltip class="box-item" effect="dark" content="编辑" placement="bottom">
                  <el-icon @click="editKey(scoped.row)">
                    <Edit />
                  </el-icon>
                </el-tooltip>
                <el-tooltip class="box-item" effect="dark" content="复制" placement="bottom">
                  <el-icon @click="handleCopy(scoped.row)">
                    <DocumentCopy />
                  </el-icon>
                </el-tooltip>
                <el-tooltip class="box-item" effect="dark" content="删除" placement="bottom">
                  <el-icon @click="deleteKey(scoped.row)" class="el-icon-danger">
                    <Delete />
                  </el-icon>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-box">
          <el-pagination v-model:current-page="keyQuery.page" v-model:page-size="keyQuery.page_size"
            :page-sizes="[20, 30, 40, 50]" :size="keyQuery.page_size" background
            layout="total, sizes, prev, pager, next, jumper" :total="keyWordTotal" @size-change="keySizeChange"
            @current-change="keyCurrentChange" />
        </div>
      </div>
      <!-- <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="dialogLog = false">
                        关闭
                    </el-button>
                </div>
            </template> -->
    </el-dialog>
    <el-dialog v-model="dialogAgent" title="配置智能体" width="800px" align-center destroy-on-close>
      <div class="dialog-box">
        <el-form ref="ruleFormRef" :model="agentForm" :rules="rules">
          <el-form-item label="选择智能体" prop="agent_id">
            <el-select v-model="agentForm.agent_id">
              <el-option v-for="item in agent_lis" :value="item.id" :label="item.name" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="联系人规则" prop="contact_rule.type" :rules="{
            required: true,
            message: '选择联系人规则',
            trigger: 'blur',
          }">
            <el-checkbox-group v-model="agentForm.contact_rule.type" style="pointer-events: none;">
              <el-checkbox label="特定用户除外" size="large" :value="1" />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="选择特定用户">
            <el-select-v2 v-model="agentForm.contact_rule.contact_ids" popper-class="costom-select" :options="cardList"
              placeholder="请选择名片" :props="v2props" filterable @change="changeCard" multiple>
              <template #default="{ item }">
                <div class="costom-select-item">
                  <el-image :src="item.avatar"></el-image>
                  <span>{{ item.nickname }}</span>
                </div>
              </template>
              <template #footer v-if="cardTotal > 100">
                <el-pagination v-model:current-page="cardPage" :page-size="50" size="small" background
                  layout="prev, pager, next" :total="cardTotal" class="mt-4" @current-change="currentChange" />
              </template>
            </el-select-v2>
          </el-form-item>
          <el-form-item label="生效开始时间" prop="effect_start_time">
            <el-time-picker v-model="agentForm.effect_start_time" value-format="HH:mm" format="HH:mm" />
          </el-form-item>
          <el-form-item label="生效结束时间" prop="effect_end_time">
            <el-time-picker v-model="agentForm.effect_end_time" value-format="HH:mm" format="HH:mm" />
            <p style="font-size: 12px;margin-top: 10px;color: var(--el-color-danger); width: 100%; line-height: 12px">
              注：若生效开始时间大于结束时间，则默认结束时间为次日</p>
          </el-form-item>
          <el-form-item label="消息合并时间（s）" prop="contact_rule.delayed_second_batch_reply" :rules="{
            required: true,
            message: '请输入消息合并时间',
            trigger: 'blur',
          }">
            <el-input-number v-model="agentForm.contact_rule.delayed_second_batch_reply" :min="1" />
          </el-form-item>
          <el-form-item label="是否启用" prop="status">
            <el-radio-group v-model="agentForm.status">
              <el-radio :label="1" size="large">启用</el-radio>
              <el-radio :label="2" size="large">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAgent" :class="{ 'no-click': mhtLoading }">

            <el-icon v-if="mhtLoading" class="mht-loading" style="margin-right: 4px;">
              <Loading />
            </el-icon>
            <el-icon style="margin-right: 4px;" v-else>
              <svg class="icon" aria-hidden="true">
                <use xlink:href="#icon-baocun"></use>
              </svg>

            </el-icon>
            保 存
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-drawer v-model="drawer" direction="rtl">
      <!-- <template #header>
                <h4>set title by slot</h4>
            </template> -->
      <template #default>
        <div class="drawer-box">

          <div style="margin-bottom: 0;">
            <label>联系人规则</label>
            <el-checkbox-group v-model="agentForm.contact_rule.type" style="pointer-events: none;">
              <el-checkbox label="特定用户除外" size="large" :value="1" style="margin-bottom: 0;" />
            </el-checkbox-group>
          </div>
          <div>
            <label>选择特定用户</label>
            <el-select-v2 v-model="agentForm.contact_rule.contact_ids" popper-class="costom-select" :options="cardList"
              placeholder="请选择名片" :props="v2props" filterable @change="changeCard" multiple>
              <template #default="{ item }">
                <div class="costom-select-item">
                  <el-image :src="item.avatar"></el-image>
                  <span>{{ item.nickname }}</span>
                </div>
              </template>
              <template #footer v-if="cardTotal > 100">
                <el-pagination v-model:current-page="cardPage" :page-size="50" size="small" background
                  layout="prev, pager, next" :total="cardTotal" class="mt-4" @current-change="currentChange" />
              </template>
            </el-select-v2>
          </div>
          <div>
            <label>生效开始时间</label>
            <el-time-picker v-model="agentForm.effect_start_time" value-format="HH:mm" format="HH:mm" />
          </div>
          <div>
            <label>生效结束时间</label>
            <el-time-picker v-model="agentForm.effect_end_time" value-format="HH:mm" format="HH:mm" />
            <p style="font-size: 12px;margin-top: 10px;color: var(--el-color-danger)">注：若生效开始时间大于结束时间，则默认结束时间为次日</p>
          </div>

          <div>
            <label>消息合并时间（s）</label>
            <el-input-number v-model="agentForm.contact_rule.delayed_second_batch_reply" :min="1" />
          </div>
          <div>
            <label>是否启用</label>
            <el-radio-group v-model="agentForm.status">
              <el-radio :label="1" size="large">启用</el-radio>
              <el-radio :label="2" size="large">禁用</el-radio>
            </el-radio-group>
          </div>
        </div>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="drawer = false">取 消</el-button>
          <el-button type="primary" @click="confirmClick">确 认</el-button>
        </div>
      </template>
    </el-drawer>


    <el-dialog v-model="dialogCopy" title="复制意图关键字" width="550px" align-center destroy-on-close>
      <div class="dialog-box">
        <el-form ref="refCopy" :model="copyTask" :rules="rulesCopy">
          <el-form-item label="将关键字复制给下面的机器人" prop="robot_id">
            <el-select-v2 style="" v-model="copyTask.robot_id" popper-class="costom-select" :options="robotCardsCopy"
              placeholder="请选择机器人" :props="v2props2" filterable @change="changeRobotCopy" clearable>
              <template #default="{ item }">
                <div class="costom-select-item">
                  <el-image :src="item.head_url"></el-image>
                  <span>{{ item.name }}</span>
                </div>
              </template>

            </el-select-v2>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogCopy = false">取 消</el-button>
          <el-button type="primary" @click="saveCopy" :class="{ 'no-click': mhtLoading }" style="margin-right: 20px;">
            <el-icon v-if="mhtLoading" class="mht-loading" style="margin-right: 4px;">
              <Loading />
            </el-icon>
            <el-icon v-else style="margin-right: 4px;">
              <svg class="icon" aria-hidden="true">
                <use xlink:href="#icon-baocun"></use>
              </svg></el-icon>

            保 存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue';
import robotStore from '@/store/modules/robotStore'
import { useRouter } from 'vue-router';
import { robotMsgLog, set_pass_request_reply, pass_request_reply_list, robot_detail, keyWordArr, deleteKeyword, contactAgent, setAgent, deleteAgent, robotList } from '@/api/robot'
import KeyWords from '@/components/KeyWords/userKeyWord.vue'
import { userList } from '@/api/user'
import { getAgents } from '@/api/ai'
import { keywords, addKeywords, addKeywordsMaterial, keywordsMaterials, upKeyword } from '@/api/keyword/userKeyWord.ts'
import { uploadFile } from '@/api/upload'
import coze from '@/assets/images/coze.png'
import dify from '@/assets/images/dify.png'
const userRobotStore = robotStore()
const router = useRouter()
const dialogWelcome = ref(false)
const toRobot = () => {
  open.value = false
  router.push('/robot')
}
const toPath = (path) => {
  router.push(path)
}
const robotInfo = ref({})
const ref1 = ref()
const open = ref(false)
const isRefresh = ref(false)
const logQuery = reactive({
  page: 1,
  page_size: 20,
  month: ''
})
const total = ref(0)
const logList = ref([])

const tableLoading = ref(false)
const getLog = async () => {
  tableLoading.value = true
  const res = await robotMsgLog({
    robot_id: robotInfo.value.id,
    ...logQuery
  })
  tableLoading.value = false
  logList.value = res.list.map(item => {
    item.content = JSON.parse(item.content)
    return item
  })
  total.value = res.total
}

const handleSizeChange = (e) => {
  logQuery.page = 1
  logQuery.page_size = e
  getLog()
}
const handleCurrentChange = (e) => {
  logQuery.page = e
  getLog()
}
const rowClassname = (e) => {
  if (e.row.status == 1) {
    return 'row-success'
  } else {
    return 'row-danger'
  }
}
const month = ref('')
const handleReMonth = (e) => {
  if (e) {
    let date = e.split('-')

    logQuery.month = date[0] + date[1]
    logQuery.page = 1
    logQuery.page_size = 20
    getLog()
  }

}
const search = () => {
  logQuery.page = 1
  getLog()
}
const disabledDate = (time) => {

  return time.getTime() > Date.now();
}
watch(robotInfo, (val) => {
  // getLog(month.value.splice('-'))
})

const load = () => {

}
const hideWelcome = () => {
  dialogWelcome.value = false
}
// const handleRefresh = () => {
//   isRefresh.value = true
//   getLog()
// }

const getRobotDetail = async () => {
  const res = await robot_detail(robotInfo.value.id)
  robotInfo.value = res
  userRobotStore.robotInfo = res
}

// 一图关键字
const dialogKeys = ref(false)
const keywordInfo = ref({})
const dialogKeywords = ref(false)
const setKeys = () => {
  dialogKeys.value = true
  getKeyWords()
}
const keyQuery = reactive({
  page: 1,
  page_size: 20,
  keyword: ''
})
const keyWordList = ref([])
const keyWordTotal = ref(0)
const tableLoading2 = ref(false)
const getKeyWords = async () => {
  tableLoading2.value = true
  const res = await keyWordArr({
    robot_id: robotInfo.value.id,
    ...keyQuery
  })
  tableLoading2.value = false
  keyWordList.value = res.list
  keyWordTotal.value = res.total
}
const keySizeChange = (e) => {
  keyQuery.page = 1
  keyQuery.page_size = e
  getKeyWords()
}
const keyCurrentChange = (e) => {
  keyQuery.page = e
  getKeyWords()
}

const addKey = () => {
  keywordInfo.value = {}
  dialogKeywords.value = true
}
const hideKey = () => {
  dialogKeywords.value = false
  keyQuery.page = 1
  getKeyWords()
}
const searchKeys = () => {
  keyQuery.page = 1
  getKeyWords()
}
const editKey = (row) => {
  keywordInfo.value = row
  dialogKeywords.value = true
}
const deleteKey = (row) => {
  ElMessageBox.confirm(
    '确认删除该关键字吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      await deleteKeyword(row.id)
      getKeyWords()
    })
    .catch(() => {

    })
}

// 智能体
const agentInfo = ref({})
// 配置智能体
const drawer = ref(false)
const dialogAgent = ref(false)
const agent_lis = ref([])
const cardPage = ref(1)
const checkAgent = async () => {
  dialogAgent.value = true
  cardPage.value == 1
  getUsers()
  const res = await getAgents({
    name: '',
    type: '',
    page: 1,
    page_size: 100
  })
  agent_lis.value = res.list
}
const ruleFormRef = ref()
const agentForm = ref({
  contact_rule: {
    type: [1]
  }
})
const rules = ref({
  agent_id: [{
    required: true,
    message: '请选择智能体',
    trigger: 'change',
  }],
  effect_start_time: [{
    required: true,
    message: '请选择生效开始时间',
    trigger: 'change',
  }],
  effect_end_time: [{
    required: true,
    message: '请选择生效结束时间',
    trigger: 'change',
  }],
  status: [{
    required: true,
    message: '请选择启用状态',
    trigger: 'change',
  }],
})

const mhtLoading = ref(false)
const submitAgent = async () => {
  await ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        mhtLoading.value = true
        let obj = JSON.parse(JSON.stringify(agentForm.value))
        obj.contact_rule.type = 1
        if (obj.contact_rule.contact_ids) {
          obj.contact_rule.contact_ids = obj.contact_rule.contact_ids.join(',')
        }
        obj.contact_rule = JSON.stringify(obj.contact_rule)
        await setAgent({
          robot_id: robotInfo.value.id,
          ...obj
        })
        dialogAgent.value = false
        getAgent()
        mhtLoading.value = false
      } catch {
        mhtLoading.value = false
      }
    }
  })
}

// 删除agent 
const deleteAi = () => {
  ElMessageBox.confirm(
    '确认删除智能体吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      await deleteAgent({
        agent_id: agentInfo.value.agent_id,
        robot_id: robotInfo.value.id
      })
      agentInfo.value = {}
    })
    .catch(() => {

    })
}

const handleSetting = () => {
  drawer.value = true
  cardPage.value == 1
  getUsers()
  agentForm.value = JSON.parse(JSON.stringify(agentInfo.value))
  agentForm.value.contact_rule = JSON.parse(agentForm.value.contact_rule)
  agentForm.value.contact_rule.type = [1]

  agentForm.value.contact_rule.contact_ids = agentForm.value.contact_rule.contact_ids.split(',')
  console.log(agentForm.value)
}
const confirmClick = async () => {
  let obj = JSON.parse(JSON.stringify(agentForm.value))
  obj.contact_rule.type = 1
  if (obj.contact_rule.contact_ids) {
    obj.contact_rule.contact_ids = obj.contact_rule.contact_ids.join(',')
  }
  obj.contact_rule = JSON.stringify(obj.contact_rule)
  await setAgent({
    robot_id: robotInfo.value.id,
    ...obj
  })
  drawer.value = false
  getAgent()
}


const cardList = ref([])

const cardTotal = ref(0)
const v2props = ref({
  value: 'user_id',
  label: 'nickname'
})
const getUsers = async () => {


  const res = await userList({
    robot_id: robotInfo.value.id,
    page: cardPage.value,
    page_size: 100
  })
  cardTotal.value = res.total
  cardList.value = res.list
  // copyCardList = res.list


}
const currentChange = (e) => {
  cardPage.value = e
  getUsers()
}

const skeleton = ref(true)
const getAgent = () => {
  contactAgent({
    robot_id: robotInfo.value.id
  }).then(res => {
    agentInfo.value = res
    skeleton.value = false
  })
}

// 比较两个时间字符串的大小
const compareTimes = (time1, time2) => {
  // 将时间字符串拆分为小时和分钟
  const [hour1, minute1] = time1.split(':').map(Number);
  const [hour2, minute2] = time2.split(':').map(Number);

  // 计算总分钟数
  const totalMinutes1 = hour1 * 60 + minute1;
  const totalMinutes2 = hour2 * 60 + minute2;

  // 比较总分钟数
  if (totalMinutes1 < totalMinutes2) {
    return -1; // time1小于time2
  } else if (totalMinutes1 > totalMinutes2) {
    return 1; // time1大于time2
  } else {
    return 0; // time1等于time2
  }
}


// 复制
const refCopy = ref()
const copyTask = ref({})
const rulesCopy = ref({
  robot_id: [
    {
      required: true,
      message: '选择机器人',
      trigger: 'change',
    }
  ]
})
const v2props2 = ref({
  value: 'id',
  label: 'name'
})
const robotCardsCopy = ref([])
const dialogCopy = ref(false)
// const mhtLoading = ref(false)
let copyMateriaList = []
let key_data = {}
const handleCopy = (row) => {
  dialogCopy.value = true
  key_data = row
  robotList({
    page: 1,
    page_size: 100
  }).then(res => {
    robotCardsCopy.value = res.list.filter(item => item.id != robotInfo.value.id)
  })
  keywordsMaterials({
    keyword_id: row.id,
    page: 1,
    page_size: 100
  }).then(res => {
    copyMateriaList = res.list.map((el) => {
      el.content = JSON.parse(el.content)
      return el
    })
  })

}
let uploadAction = ''
const changeRobotCopy = (e) => {
  robotCardsCopy.value.forEach((el) => {
    if (e == el.id) {
      copyTask.value.robot_id = el.id
      uploadAction = el.server_ip
    }
  })
}

const convertImageUrlToFile = async (url, fileName) => {
  try {
    // 1. 获取图片数据
    console.log(url)
    const response = await fetch(url);
    if (!response.ok) throw new Error('图片下载失败');

    // 2. 将响应转换为 Blob
    const blob = await response.blob();
    // 创建 FormData 对象
    const formData = new FormData();
    // 生成文件名
    formData.append('file', blob, fileName);
    // // 3. 将 Blob 转换为 File 对象（模拟用户上传的文件）
    // const file = new File([blob], fileName, { type: blob.type });

    return formData;
  } catch (error) {
    console.error('转换失败:', error);
    throw error;
  }

}

const saveCopy = async () => {
  await refCopy.value.validate(async (valid, fields) => {
    if (valid) {
      mhtLoading.value = true
      const promises = copyMateriaList.map(async (el, i) => {
        let url = ''
        let fileName = ''
        if (el.type == 2 || el.type == 4) {
          url = el.content.img_url
          fileName = el.content.file_name
          const file = await convertImageUrlToFile(url, fileName)
          let fordata = new FormData();
          fordata.append('file', file)
          const data = await uploadFile(file, uploadAction)
          copyMateriaList[i].content.img_url = uploadAction + '/' + data.file_url
          copyMateriaList[i].content.file_path = data.file_path
          return true
        } else if (el.type == 8 || el.type == 10) {
          url = el.content.file_url
          fileName = el.content.file_name
          const file = await convertImageUrlToFile(url, fileName)
          let fordata = new FormData();
          fordata.append('file', file)
          const data = await uploadFile(file, uploadAction)
          copyMateriaList[i].content.file_url = uploadAction + '/' + data.file_url
          copyMateriaList[i].content.file_path = data.file_path
          return true
        }

      })
      Promise.all(promises)
        .then(async (results) => {
          console.log('所有图片都已完成', results);
          console.log(copyMateriaList)
          try {
            // const obj = JSON.parse(JSON.stringify(copyTask.value))
            // obj.robot_id = String(copyTask.value.robot_id)
            const resKeys = await addKeywords({
              "keyword": key_data.keyword,
              "robot_id": copyTask.value.robot_id,
            })
            const key_id = resKeys.id

            await addKeywordsMaterial({
              'material_list': copyMateriaList.map((el) => {
                return {
                  content: JSON.stringify(el.content),
                  type: el.type,
                  interval_seconds: el.interval_seconds
                }
              })

            }, key_id)
            mhtLoading.value = false
            dialogCopy.value = false
            ElNotification({
              type: 'success',
              message: '复制成功'
            })

          } catch (err) {
            mhtLoading.value = false
          }

        })
        .catch((error) => {
          mhtLoading.value = false
          console.error('有图片失败了', error);
        });
    }
  })

}
onMounted(() => {
  robotInfo.value = userRobotStore.robotInfo
  if (robotInfo.value.id) {
    getRobotDetail()
    getAgent()
    let date = new Date().toLocaleDateString().split('/')
    if (date[1] < 10) {
      date[1] = '0' + date[1]
    }
    month.value = date[0] + '-' + date[1]
    logQuery.month = date[0] + date[1]
    getLog()
  } else {
    setTimeout(() => {
      open.value = true
    }, 500)
  }
})
</script>
<style></style>
<style scoped lang="scss">
.container {
  padding: var(--el-main-padding);

  .robot-card {
    // height: 160px;

    // :deep(.el-card__body) {
    //   height: 100%;
    // }
    margin-bottom: 20px;

    .unrobot-box {
      height: 70px;
      // display: flex;
      // justify-content: center;
      // align-items: center;
      // text-align: center;
      // line-height: 70px;
      overflow: hidden;

      .el-icon {
        float: left;
        font-size: 70px;
      }

      .el-button {
        width: 150px;
        float: right;
        position: relative;
        top: 50%;
        transform: translateY(-50%);
      }
    }

    .robot-box {
      height: 100px;
      overflow: hidden;
      padding-top: 16px;
      padding-left: 20px;

      .robot-info {
        float: left;
        padding-left: 15px;

        .robot-name {
          font-size: 15px;
          font-weight: bold;
          margin-top: 6px;
          margin-bottom: 8px;
        }

        .wx-name {
          color: var(--el-text-color-regular);
          font-size: 14px;
          margin-bottom: 8px;
        }

        .robot-id {
          color: var(--el-text-color-regular);
          font-size: 14px;
        }
      }

      .robot-obj {
        float: right;

        .obj-flex {
          display: flex;
        }

        .obj-reply {
          margin-top: 16px;
          font-size: 12px;
          text-align: right;
          cursor: pointer;
          margin-right: 10px;

          .el-icon {
            color: var(--el-color-primary);
            cursor: pointer;
            margin-left: 6px;
            font-size: 16px;
            transform: translateY(4px);
          }
        }

        .obj-item {
          flex: 1;
          // width: 60px;
          text-align: center;
          height: 44px;

          label {
            color: var(--el-text-color-regular);
            font-size: 14px;
            display: block;
            margin-bottom: 10px;
            // margin-top: 15px;
            white-space: nowrap;
            display: inline-block;
            padding: 0 10px;
          }

          span {
            font-size: 18px;
            font-weight: bold;
            color: var(--el-color-primary);
            cursor: pointer;
          }
        }
      }
    }

    .robot-head {
      float: left;
      width: 70px;
      height: 70px;
      border-radius: 10px;
    }
  }

  .robot-contact-group {
    height: calc(100vh - 620px);

    .contact-group {
      height: calc(100% - 20px);
      text-align: center;
      line-height: 1;
      font-size: 50px;
      font-weight: bold;
      color: var(--el-color-primary);
      display: flex;
      justify-content: center;
      align-items: center;

      span {
        cursor: pointer;

      }
    }
  }

  .title-label {
    font-size: 15px;
    color: var(--el-text-color-regular);
    font-weight: bold;
  }

  .robot-log {
    // margin-top: 20px;
    height: calc(100vh - 260px);

    .infinite-list {
      height: calc(100% - 40px);
      padding: 0;
      margin-top: 15px;
      list-style: none;
    }

    .infinite-list .infinite-list-item {
      // display: flex;
      // align-items: center;
      // justify-content: center;
      font-size: 13px;
      height: 40px;
      line-height: 40px;
      background: var(--el-color-primary-light-9);
      margin: 10px;
      color: var(--el-color-primary);
      padding: 0 20px;
      white-space: nowrap;

      .remark {
        float: left;
      }

      .created_at {
        float: right;
      }
    }

    .infinite-list .infinite-list-item+.list-item {
      margin-top: 10px;
    }
  }

  .refresh {
    position: absolute;
    right: 40px;
    font-size: 20px;
    cursor: pointer;
    color: var(--el-color-primary);
  }

  .loadingIcon {
    transform: rotate(45deg);
    animation: spin 1s linear infinite;
  }

  @keyframes spin {
    from {
      transform: rotate(0deg);
    }

    to {
      transform: rotate(360deg);
    }
  }

  .message-box {
    padding: 0px 30px;
    line-height: 20px;
    width: 90wh;
    white-space: normal;
    word-break: break-all;
  }
}

.agent-no {
  text-align: center;
  margin-top: 25px;
}

.agent-info {
  margin-top: 14px;
  // padding-left: 20px;
  font-size: 14px;
  line-height: 22px;
  position: relative;
  overflow: hidden;

  .el-image {
    float: left;
    width: 50px;
    height: 50px;
    border-radius: 8px;
  }

  .robot-icon {
    float: left;
    width: 60px;
    height: 50px;
    border-radius: 8px;
    // transform: translateY(4px);
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: var(--el-color-primary-light-3);
    color: #fff;
    font-size: 13px;
    font-weight: bold;

    span {
      transform: scaleY(1.3);
    }
  }

  .agent-box {
    float: left;
    width: calc(100% - 60px);
    padding-left: 10px;
    font-size: 13px;

    .name {
      font-size: 14px;
    }
  }








}

.agent-btn {
  position: absolute;
  right: 20px;
  top: 20px;
  font-size: 13px;

  .el-icon {
    font-size: 18px;
    cursor: pointer;
    color: var(--el-color-primary);
  }

}

.setting {
  position: absolute;
  top: 20px;
  right: 20px;
  text-align: right;

  .el-icon {
    color: var(--el-color-primary);
    cursor: pointer;
    font-size: 18px;
    margin-bottom: 6px;
  }

  span {
    font-size: 12px;
    line-height: 20px;
  }

  .disable {
    position: relative;
    color: var(--el-color-danger);

    &::after {
      position: absolute;
      left: -15px;
      top: 4px;
      content: '';
      width: 8px;
      height: 8px;
      border-radius: 8px;
      background-color: var(--el-color-danger);
    }
  }

  .enable {
    position: relative;
    color: var(--el-color-success);

    &::after {
      position: absolute;
      left: -15px;
      top: 4px;
      content: '';
      width: 8px;
      height: 8px;
      border-radius: 8px;
      background-color: var(--el-color-success);
    }
  }

  .delete {
    cursor: pointer;
    margin-left: 12px;
    color: var(--el-color-danger);

    &:hover {
      opacity: 0.7;
    }
  }
}

.description {
  height: 18px;
  line-height: 18px;
  font-size: 13px;
  color: var(--el-text-color-regular);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-top: 10px;
  // padding-left: 20px;
}

.drawer-box {
  padding: 0 20px;

  &>div {
    margin-bottom: 20px;
  }

  label {
    display: block;
    font-size: 14px;
    margin-bottom: 15px;
  }
}
</style>