<template>
  <div class="form-wrap geek-auto-start-run-with-boss">
    <el-form ref="formRef" :model="formContent" label-position="top" :rules="formRules">
      <el-form-item label="BOSS直聘 Cookie">
        <el-button size="small" type="primary" @click="handleClickLaunchLogin"
          >编辑Cookie</el-button
        >
      </el-form-item>
      <!-- <el-form-item
        label="钉钉机器人 AccessToken（用于记录开聊，请勿使用公司内部群）"
        prop="dingtalkRobotAccessToken"
      >
        <el-input v-model="formContent.dingtalkRobotAccessToken" />
      </el-form-item> -->
      <div>
        <el-form-item mb0>
          <div>
            是否查看职位详情的条件
            <span font-size-12px>（以下条件为空表示不筛选）</span>
          </div>
        </el-form-item>
        <el-form-item prop="expectCompanies" mb10px>
          <div
            v-full
            font-size-12px
            flex
            :style="{
              justifyContent: 'space-between',
              alignItems: 'center',
              width: '100%'
            }"
          >
            <div>
              期望公司（以逗号分隔，不区分大小写）<el-tooltip
                effect="light"
                placement="bottom-start"
                @show="gtagRenderer('tooltip_show_about_expect_company_figure')"
              >
                <template #content>
                  <img block h-270px src="./resources/intro-of-job-entry.png" />
                </template>
                <el-button type="text" font-size-12px
                  ><span><QuestionFilled w-1em h-1em mr2px /></span>期望公司信息位置图示</el-button
                >
              </el-tooltip>
            </div>
            <el-dropdown @command="handleExpectCompanyTemplateClicked">
              <el-button size="small"
                >期望公司模板 <el-icon class="el-icon--right"><arrow-down /></el-icon
              ></el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-for="item in expectCompanyTemplateList"
                    :key="item.name"
                    :command="item"
                    >{{ item.name }}</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
          <el-input
            v-model="formContent.expectCompanies"
            :autosize="{ minRows: 4 }"
            max-h-8lh
            type="textarea"
            @blur="normalizeExpectCompanies"
          />
        </el-form-item>
      </div>
      <div mb42px>
        <el-form-item mb0>
          查看职位详情后，是发起投递还是标记不合适的条件
          <span font-size-12px>（以下条件为空表示不筛选）</span>
        </el-form-item>
        <div
          flex
          :style="{
            alignItems: 'center',
            justifyContent: 'space-between'
          }"
        >
          <div>
            <el-tooltip
              effect="light"
              placement="bottom"
              @show="gtagRenderer('tooltip_show_about_expect_job_info_figure')"
            >
              <template #content>
                <img block h-270px src="./resources/intro-of-job-info.png" />
              </template>
              <el-button type="text" font-size-12px
                ><span><QuestionFilled w-1em h-1em mr2px /></span>如下各信息位置图示</el-button
              >
            </el-tooltip>
            <el-tooltip
              effect="light"
              placement="bottom-start"
              @show="gtagRenderer('tooltip_show_about_mark_not_suit_intro')"
            >
              <template #content>
                <ol m0 line-height-1.5em w-400px pl2em>
                  <li>
                    如果查找到的职位，职位名称、职位类型、职位描述与如下正则不匹配，则这个职位将被标记为不合适
                  </li>
                  <li>
                    如果查找到的职位活跃时间为“本月活跃”或更往前的时间，则这个职位将被标记为不合适
                  </li>
                  <li>
                    如有错误标记，请在左侧“<a
                      href="javascript:void(0)"
                      style="color: var(--el-color-primary)"
                      @click.prevent="
                        () => {
                          gtagRenderer('click_view_mansr_from_boss_b_tooltip')
                          $router.push('/main-layout/MarkAsNotSuitRecord')
                        }
                      "
                      >标记不合适</a
                    >”记录中找到相关记录，手动对这些职位发起会话
                  </li>
                </ol>
              </template>
              <el-button type="text" font-size-12px
                ><span><QuestionFilled w-1em h-1em mr2px /></span>标记不合适机制</el-button
              >
            </el-tooltip>
          </div>
          <el-dropdown ml20px @command="handleExpectJobFilterTemplateClicked">
            <el-button size="small"
              >职位详情筛选模板（按职类区分）
              <el-icon class="el-icon--right"><arrow-down /></el-icon
            ></el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  v-for="item in expectJobFilterTemplateList"
                  :key="item.name"
                  :command="item"
                  >{{ item.name }}</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <div
          :style="{
            display: 'grid',
            gridTemplateColumns: '1fr 1em 1fr 1em 1fr',
            gap: '5px',
            width: '100%',
            alignItems: 'end'
          }"
        >
          <el-form-item mb0 prop="expectJobNameRegExpStr">
            <div font-size-12px>职位名称正则（不区分大小写）</div>
            <el-input
              v-model="formContent.expectJobNameRegExpStr"
              @blur="
                formContent.expectJobNameRegExpStr =
                  formContent.expectJobNameRegExpStr?.trim() ?? ''
              "
            />
          </el-form-item>
          <div mb10px font-size-12px flex flex-justify-center>且</div>
          <el-form-item mb0 prop="expectJobTypeRegExpStr">
            <div font-size-12px>职位类型正则（不区分大小写）</div>
            <el-input
              v-model="formContent.expectJobTypeRegExpStr"
              @blur="
                formContent.expectJobTypeRegExpStr =
                  formContent.expectJobTypeRegExpStr?.trim() ?? ''
              "
            />
          </el-form-item>
          <div mb10px font-size-12px flex flex-justify-center>且</div>
          <el-form-item mb0 prop="expectJobDescRegExpStr">
            <div font-size-12px>职位描述正则（不区分大小写）</div>
            <el-input
              v-model="formContent.expectJobDescRegExpStr"
              @blur="
                formContent.expectJobDescRegExpStr =
                  formContent.expectJobDescRegExpStr?.trim() ?? ''
              "
            />
          </el-form-item>
        </div>
      </div>
      <el-form-item
        label="职位备选筛选条件（当前求职期望无合适职位时，自动更改Boss筛选条件，查找新工作）"
        prop="filter"
        mb0
      >
        <AnyCombineBossRecommendFilter v-model="formContent.anyCombineRecommendJobFilter" />
        <div>
          当前组合条件数：{{ currentAnyCombineRecommendJobFilterCombinationCount.toLocaleString() }}
          <span
            v-if="currentAnyCombineRecommendJobFilterCombinationCount >= 20"
            class="color-orange"
            >不建议选择太多组合条件</span
          >
        </div>
      </el-form-item>
      <el-form-item class="last-form-item mb0">
        <el-button @click="handleSave">仅保存配置</el-button>
        <el-button type="primary" @click="handleSubmit"> 保存配置，并开始求职！ </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { ElForm, ElMessage } from 'element-plus'
import { QuestionFilled } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import AnyCombineBossRecommendFilter from '@renderer/features/AnyCombineBossRecommendFilter/index.vue'
import { calculateTotalCombinations } from '@geekgeekrun/geek-auto-start-chat-with-boss/combineCalculator.mjs'
import { gtagRenderer } from '@renderer/utils/gtag'
import defaultTargetCompanyListConf from '@geekgeekrun/geek-auto-start-chat-with-boss/default-config-file/target-company-list.json'
import { ArrowDown } from '@element-plus/icons-vue'

const router = useRouter()

const formContent = ref({
  dingtalkRobotAccessToken: '',
  expectCompanies: '',
  anyCombineRecommendJobFilter: {},
  expectJobNameRegExpStr: '',
  expectJobTypeRegExpStr: '',
  expectJobDescRegExpStr: ''
})

const currentAnyCombineRecommendJobFilterCombinationCount = computed(() => {
  return calculateTotalCombinations(formContent.value.anyCombineRecommendJobFilter)
})

electron.ipcRenderer.invoke('fetch-config-file-content').then((res) => {
  console.log(res)
  formContent.value.dingtalkRobotAccessToken = res.config['dingtalk.json']['groupRobotAccessToken']
  formContent.value.expectCompanies = res.config['target-company-list.json'].join(',')
  formContent.value.anyCombineRecommendJobFilter = res.config['boss.json']
    ?.anyCombineRecommendJobFilter ?? {
    salaryList: [],
    experienceList: [],
    degreeList: [],
    scaleList: [],
    industryList: []
  }
  //
  if (
    res.config['boss.json']?.expectJobRegExpStr &&
    typeof res.config['boss.json']?.expectJobNameRegExpStr === 'undefined' &&
    typeof res.config['boss.json']?.expectJobTypeRegExpStr === 'undefined' &&
    typeof res.config['boss.json']?.expectJobDescRegExpStr === 'undefined'
  ) {
    res.config['boss.json'].expectJobNameRegExpStr = res.config['boss.json'].expectJobRegExpStr
    res.config['boss.json'].expectJobTypeRegExpStr = res.config['boss.json'].expectJobRegExpStr
    res.config['boss.json'].expectJobDescRegExpStr = res.config['boss.json'].expectJobRegExpStr
  }
  formContent.value.expectJobNameRegExpStr = res.config['boss.json'].expectJobNameRegExpStr?.trim()
  formContent.value.expectJobTypeRegExpStr = res.config['boss.json'].expectJobTypeRegExpStr?.trim()
  formContent.value.expectJobDescRegExpStr = res.config['boss.json'].expectJobDescRegExpStr?.trim()
})

const formRules = {
  expectJobNameRegExpStr: {
    validator(_, value, cb) {
      if (!value) {
        cb()
        gtagRenderer('empty_reg_exp_for_expect_job_name')
        return
      }
      try {
        new RegExp(value, 'ig')
        gtagRenderer('valid_reg_exp_for_expect_job_name')
        cb()
      } catch (err) {
        cb(new Error(`正则无效：${err?.message}`))
        gtagRenderer('invalid_reg_exp_for_expect_job_name')
      }
    }
  },
  expectJobTypeRegExpStr: {
    validator(_, value, cb) {
      if (!value) {
        cb()
        gtagRenderer('empty_reg_exp_for_expect_job_type')
        return
      }
      try {
        new RegExp(value, 'ig')
        gtagRenderer('valid_reg_exp_for_expect_job_type')
        cb()
      } catch (err) {
        cb(new Error(`正则无效：${err?.message}`))
        gtagRenderer('invalid_reg_exp_for_expect_job_type')
      }
    }
  },
  expectJobDescRegExpStr: {
    validator(_, value, cb) {
      if (!value) {
        cb()
        gtagRenderer('empty_reg_exp_for_expect_job_desc')
        return
      }
      try {
        new RegExp(value, 'ig')
        gtagRenderer('valid_reg_exp_for_expect_job_desc')
        cb()
      } catch (err) {
        cb(new Error(`正则无效：${err?.message}`))
        gtagRenderer('invalid_reg_exp_for_expect_job_desc')
      }
    }
  }
}

const formRef = ref<InstanceType<typeof ElForm>>()
const handleSubmit = async () => {
  gtagRenderer('save_config_and_launch_clicked', {
    has_dingtalk_robot_token: !!formContent.value?.dingtalkRobotAccessToken
  })
  formContent.value.expectJobRegExpStr = undefined
  try {
    await formRef.value!.validate()
  } catch (err) {
    ElMessage.error({
      message: '表单校验失败，请检查有误的内容',
      grouping: true
    })
    console.log(err)
    return
  }
  await electron.ipcRenderer.invoke('save-config-file-from-ui', JSON.stringify(formContent.value))
  router.replace({
    path: '/geekAutoStartChatWithBoss/prepareRun',
    query: { flow: 'geek-auto-start-chat-with-boss' }
  })
  gtagRenderer('config_saved_and_launch_auto_start_chat', {
    has_dingtalk_robot_token: !!formContent.value?.dingtalkRobotAccessToken
  })
}
const handleSave = async () => {
  gtagRenderer('save_config_clicked', {
    has_dingtalk_robot_token: !!formContent.value?.dingtalkRobotAccessToken
  })
  normalizeExpectCompanies()
  try {
    await formRef.value!.validate()
  } catch (err) {
    ElMessage.error({
      message: '表单校验失败，请检查有误的内容',
      grouping: true
    })
    console.log(err)
    return
  }
  await electron.ipcRenderer.invoke('save-config-file-from-ui', JSON.stringify(formContent.value))
  ElMessage.success('配置保存成功')
  gtagRenderer('config_saved')
}

const normalizeExpectCompanies = () => {
  formContent.value.expectCompanies = formContent.value.expectCompanies
    .split(/,|，/)
    .map((it) => it.trim())
    .filter(Boolean)
    .join(',')
}

const handleClickLaunchLogin = () => {
  gtagRenderer('launch_login_clicked')
  router.replace('/cookieAssistant')
}
const expectCompanyTemplateList = [
  {
    name: '默认值',
    value: defaultTargetCompanyListConf.join(',')
  },
  {
    name: '不限公司（随便投）',
    value: ''
  },
  {
    name: '大厂及关联企业',
    value: `抖音,字节,字跳,有竹居,脸萌,头条,懂车帝,滴滴,嘀嘀,小桔,网易,有道,腾讯,酷狗,酷我,阅文,搜狗,京东,沃东天骏,达达,达冠,百度,度小满,爱奇艺,携程,趣拿,去哪儿,集度,理想,蔚来,顺丰,讯飞,同程,艺龙,马蜂窝,贝壳,自如,链家,我爱我家,相寓,多点,金山,小米,猎豹,新浪,微博,阿里,蚂蚁,飞猪,乌鸫,饿了么,LAZADA,来赞达,飞猪,菜鸟,哈啰,钉钉,高德,美团,三快,猫眼,快手,映客,小红书,行吟,奇虎,360,三六零,鸿盈,奇富,奇元,亚信,启明星辰,奇安信,深信服,长亭,绿盟,天融信,商汤,SenseTime,大华,海康威视,hikvision,汽车之家,车好多,瓜子,易车,昆仑万维,昆仑天工,闲徕,趣加,FunPlus,完美,马上消费,轻松,水滴,白龙马,58,车欢欢,五八,红布林,致美,快狗,天鹅到家,转转,美餐,知乎,智者四海,易点云,搜狐,用友,畅捷通,猿辅导,小猿,猿力,好未来,学而思,希望学,新东方,东方甄选,东方优选,作业帮,高途,跟谁学,学科网,天学网,一起教育,一起作业,美术宝,火花思维,粉笔,老虎国际,一心向上,向上一意,联想,拉勾,乐视,欢聚,竞技世界,拼多多,寻梦,得物,Moka,希瑞亚斯,北森,OPPO,欧珀,vivo,维沃,小天才,步步高,读书郎,货拉拉,陌陌,探探,Shopee,首汽租车,神州租车,天眼查,旷视,小冰,美图,智谱华章,MiniMax,石头科技,迅雷,TP,希音,SHEIN,稀宇,深言,百川智能,与爱为舞,牵手`
  },
  {
    name: '阿里系',
    value: `阿里,蚂蚁,飞猪,乌鸫,饿了么,LAZADA,来赞达,菜鸟,哈啰,钉钉,高德,白龙马,新浪,微博`
  },
  {
    name: '字节（头条/抖音）系',
    value: `抖音,字节,字跳,有竹居,脸萌,头条,懂车帝`
  },
  {
    name: '百度系',
    value: `百度,度小满,爱奇艺,携程,趣拿,集度,作业帮`
  },
  {
    name: '腾讯系',
    value: `腾讯,酷狗,酷我,阅文,搜狗,京东,沃东天骏,达达,达冠,美团,三快,猫眼,快手,拼多多,寻梦,Shopee,滴滴,嘀嘀,小桔`
  },
  {
    name: '外包、劳务派遣企业',
    value: `青钱,软通动力,南天,睿服,中电金信,佰钧成,云链,博彦,汉克时代,柯莱特,拓保,亿达信息,纬创,微创,微澜,诚迈科技,法本,兆尹,诚迈,联合永道,新致软件,宇信科技,华为,德科,FESCO,科锐,科之锐`
  }
]
function handleExpectCompanyTemplateClicked(item) {
  gtagRenderer('expect_company_tpl_clicked', {
    name: item.name
  })
  formContent.value.expectCompanies = item.value
}

const expectJobFilterTemplateList = [
  {
    name: '不限职位（随便投）',
    config: {
      expectJobNameRegExpStr: '',
      expectJobTypeRegExpStr: '',
      expectJobDescRegExpStr: ''
    }
  },
  {
    name: '研发 - 前端开发工程师',
    config: {
      expectJobNameRegExpStr: '前端|H5|FE',
      expectJobTypeRegExpStr: '前端开发|javascript',
      expectJobDescRegExpStr: '前端|vue|react|node|js|javascript|H5'
    }
  },
  {
    name: '研发 - Java',
    config: {
      expectJobNameRegExpStr: 'Java',
      expectJobTypeRegExpStr: 'Java',
      expectJobDescRegExpStr: 'JVM|Java|消息队列|MySQL|Nginx|Redis|Dubbo'
    }
  },
  {
    name: '人力 - 员工关系',
    config: {
      expectJobNameRegExpStr: '员工关系|劳动关系|SSC|人力资源|人资',
      expectJobTypeRegExpStr: '员工关系|人力资源',
      expectJobDescRegExpStr: '社保|考勤|入职|离职'
    }
  },
  {
    name: '人力 - 招聘',
    config: {
      expectJobNameRegExpStr: '招聘|招聘HR|招聘专员|招聘顾问|招聘专家|Recruiter|人力资源|人资',
      expectJobTypeRegExpStr: '招聘|人力资源|猎头顾问',
      expectJobDescRegExpStr: '简历筛选|面试安排|offer|猎头'
    }
  }
]
function handleExpectJobFilterTemplateClicked(item) {
  gtagRenderer('expect_job_filter_tpl_clicked', {
    name: item.name
  })

  Object.assign(formContent.value, {
    ...item.config
  })
}
</script>

<style scoped lang="scss">
.form-wrap {
  margin: 0 auto;
  max-width: 1000px;
  max-height: 100vh;
  overflow: auto;
  padding-left: 20px;
  padding-right: 20px;
  :deep(.el-form) {
    padding-top: 8px;
  }
  .last-form-item {
    :deep(.el-form-item__content) {
      margin-top: 0px;
      justify-content: flex-end;
    }
  }
}
</style>

<style lang="scss">
.form-wrap.geek-auto-start-run-with-boss {
  .el-form-item__error.el-form-item__error {
    font-size: 12px;
    line-height: 1.2em;
  }
}
</style>
