<template>
  <Dialog :dialogVisible="dialogShow" @confirm="confirmEvent" @close="closeEvent" :cancleText="pageInfo.cancleText"
    :closeOnModal="false" :hasBtn="pageInfo.hasBtn" :destroyOnCloseFlag="true" width="800px" dialog-title="批量修改日预算">
    <template v-slot:content>
      <div class="dialogBox" v-if="pageInfo.schedule == 1">
        <div class="batch-title">已选{{ pageInfo.multipleSelection.length }}个可操作媒体账户</div>
        <div class="flex bMar15">
          <span class="form-block-item-title">修改规则</span>
          <el-radio-group v-model="pageInfo.modifyRuleValue" size="default">
            <template v-for="item in modifyRule">
              <el-radio-button :label="item.value">{{ item.label }}</el-radio-button>
            </template>
          </el-radio-group>
        </div>
        <div class="flex_start bMar15">
          <span class="form-block-item-title">预算</span>
          <div class="flex_start">
            <el-select v-model="pageInfo.selectValue" style="width: 115px" @change="selectChange">
              <el-option :label="item.label" :value="item.value" v-for="item in selectList" />
            </el-select>
            <div>
              <el-input v-model="pageInfo.inputValue" :class="pageInfo.mainInputError ? 'inputError' : ''"
                v-if="pageInfo.selectValue != 6" style="width:260px" @input="onChangeInput('mainInput')">
                <template #suffix>
                  <span>{{ selectList.filter((v) => v.value == pageInfo.selectValue)[0]?.unit }}</span>
                </template>
              </el-input>
              <div class="error" v-if="pageInfo.mainInputError">{{ pageInfo.mainInputErrHint }}</div>
            </div>
            <el-tooltip placement="top" content="选中广告主账户预算包含不限，不可以设置此内容"
              :disabled="!(pageInfo.selectValue == 1 || pageInfo.selectValue == 6 ? false : pageInfo.isNoLimit)"
              effect="light">
              <span>
                <el-button type="primary" class="lMar10"
                  :disabled="pageInfo.selectValue == 1 || pageInfo.selectValue == 6 ? false : pageInfo.isNoLimit"
                  @click="application">应 用</el-button>
              </span>
            </el-tooltip>
          </div>
        </div>
        <!-- 更改预算 table -->
        <el-table :data="pageInfo.multipleSelection" :header-cell-style="tableHeaderStyle" border style="width: 100%">
          <el-table-column prop="advertiser_id" label="广告主账户" width="180" />
          <el-table-column label="日预算" width="180" align="right">
            <template #default="scope">
              {{ scope.row.daily_budget || '不限' }}
            </template>
          </el-table-column>
          <el-table-column label="分别修改日预算">
            <template #default="scope">
              <el-input v-model="scope.row.modifyDailyBudget"
                :class="scope.row.inputError != '' && scope.row.inputError ? 'inputError' : ''" placeholder="请输入日预算"
                style="width:260px" @input="onChangeInput('tableInput', scope.$index)"></el-input>
              <div class="error" v-if="scope.row.inputError">{{ scope.row.inputError }}</div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 确定修改操作 -->
      <div class="dialogBox" v-if="pageInfo.schedule == 2 || pageInfo.schedule == 3">
        <div class="flex bMar15" v-if="pageInfo.schedule == 2">
          <el-icon color="#ff9b48">
            <WarningFilled />
          </el-icon>
          <p class="f13 c-555 lMar5">确定要执行以下修改操作吗？此操作不可逆！</p>
        </div>
        <div class="flex bMar15" v-if="pageInfo.schedule == 3">
          <el-icon color="#00b697">
            <CircleCheckFilled />
          </el-icon>
          <p class="f13 c-555 lMar5">修改完成，共{{ pageInfo.successLength }}项修改成功</p>
        </div>
        <el-table :data="pageInfo.multipleSelection" :header-cell-style="tableHeaderStyle" border style="width: 100%">
          <el-table-column prop="advertiser_id" label="广告主账户" />
          <el-table-column label="日预算">
            <template #default="scope">
              <div class="preview-modified">
                <div class="budget">{{ scope.row.daily_budget || '不限' }}</div>
                <div class="modified-info">
                  <div class="status">
                    <div class="text">{{ scope.row.modifyDailyBudget && scope.row.modifyDailyBudget != '' ? '修改为' :
                      '(未修改)' }}</div>
                  </div>
                  <div class="modified-budget">{{ scope.row.modifyDailyBudget }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="修改结果" v-if="pageInfo.schedule == 3" width="180px">
            <template #default="scope">
              <div class="flex" v-if="scope.row.state != 2 && (scope.row.modifyDailyBudget && scope.row.modifyDailyBudget != '')">
                <el-icon color="#00b697" class="rMar5">
                  <CircleCheckFilled />
                </el-icon>
                <span>修改成功</span>
              </div>
              <div class="flex" v-if="scope.row.state == 2">
                <el-icon color="#fb1919" class="rMar5">
                  <CircleCloseFilled />
                </el-icon>
                <span>失败：{{ scope.row.err_msg }}</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import Dialog from '@/components/capsulationMoudle/_dialog.vue'
import { nextTick, onMounted, reactive, ref } from "vue";
import { ElLoading, ElMessage } from "element-plus";
import _ from 'lodash';
import http from '@/http/http'
import { getDay } from '@/common/common';

const emit = defineEmits<{
  (event: "confirm", val: string): void;
}>();

const props = withDefaults(defineProps<{
  title?: string,
}>(), {
  title: '提示',
})

const modifyRule = [
  { label: '立即生效', value: 1 },
  { label: '次日0时生效', value: 2 }
]
const selectList = [
  { label: '修改为', value: 1, unit: '元' },
  { label: '提高', value: 2, unit: '元' },
  { label: '降低', value: 3, unit: '元' },
  { label: '按 % 提高', value: 4, unit: '%' },
  { label: '按 % 降低', value: 5, unit: '%' },
  { label: '不限', value: 6, unit: '' },
]
const pageInfo: any = reactive({})
const nameRef = ref<{ value: any }>()
const confirmEvent = async () => {
  if (pageInfo.schedule == 1) {
    let isErrItem = false;
    let isEmpty = false
    pageInfo.multipleSelection.forEach((item) => {
      if (item.inputError && item.inputError != '') {
        isErrItem = true
      }
      if (item.modifyDailyBudget && item.modifyDailyBudget != '') {
        isEmpty = true;
      }
    })
    if (isErrItem) {
      ElMessage.error('存在不合法日预算，请重新填写不合法的日预算')
      return
    }
    if (!isEmpty) {
      ElMessage.error(' 请修改至少一个广告主账户的日预算！')
      return
    }
    pageInfo.schedule = 2;
    pageInfo.cancleText = '返回编辑'
    return;
  }
  if (pageInfo.schedule == 2) {
    const loading = ElLoading.service({
      lock: true,
      text: '修改操作进行中...',
      background: 'rgba(255, 255, 255, 0.7)',
    })
    let str_val: any[] = []
    pageInfo.multipleSelection.forEach((item) => {
      if (item.modifyDailyBudget && item.modifyDailyBudget != '') {
        str_val.push({
          "account_id": item.advertiser_id,
          "daily_budget": item.modifyDailyBudget == '不限' ? 0 : item.modifyDailyBudget
        })
      }
    })

    let params = {
      'str_val': JSON.stringify(str_val)
    }
    if (pageInfo.modifyRuleValue == 1) {
      params['start_time'] = getDay(0, true).now
    }
    if (pageInfo.modifyRuleValue == 2) {
      params['start_time'] = getDay(1, false) + ' 00:00:00'
    }
    const res: any = await http.post('/api/ad/multiUpDailyBudget', params)
    loading.close()
    if (res.errNo == 0) {
      ElMessage.success('修改成功')
      if (res.rst.record_id) {
        getMultiUpDailyBudgetRes(res.rst.record_id, str_val)
      }
    } else {
      ElMessage.error(res.errMsg)
    }
    return
  }
}
/**获取批量修改日预算结果 */
const getMultiUpDailyBudgetRes = async (record_id, str_val) => {
  const loading = ElLoading.service({
    lock: true,
    text: '结果获取中...',
    background: 'rgba(255, 255, 255, 0.7)',
  })
  const res: any = await http.get('/api/ad/multiUpDailyBudgetRes', { record_id })
  loading.close()
  if (res.errNo == 0) {
    pageInfo.schedule = 3;
    pageInfo.cancleText = '关闭'
    pageInfo.hasBtn = true;
    if (Array.isArray(res.rst.result)) {
      pageInfo.multipleSelection.forEach((item) => {
        let arr = str_val.filter((v) => v.account_id == item.advertiser_id)
        if (arr.length > 0) {
          let brr = res.rst.result.filter((v) => { v.account_id == arr[0].account_id })
          if (brr.length > 0) {
            item['state'] = brr[0].state
            item['err_msg'] = brr[0].err_msg
          }
        }
      })
      pageInfo.successLength = str_val.length - res.rst.result?.length
    } else {
      pageInfo.successLength = str_val.length
    }
  } else {
    ElMessage.error(res.errMsg)
  }
}
const closeEvent = () => {
  if (pageInfo.schedule == 1) {
    dialogShow.value = false
  }
  if (pageInfo.schedule == 2) {
    pageInfo.schedule = 1;
    pageInfo.cancleText = '取消'
  }
  if (pageInfo.schedule == 3) {
    dialogShow.value = false
    emit('confirm', '')
  }
}
/**点击应用 */
const application = () => {
  if ((pageInfo.selectValue != 1 && pageInfo.selectValue != 6 && pageInfo.isNoLimit) || pageInfo.mainInputError) {
    ElMessage.error('预算批量规则设置有误')
    return
  }
  if (pageInfo.selectValue != 6 && pageInfo.inputValue == '') {
    pageInfo.mainInputErrHint = '请输入账户日预算，仅支持正整数'
    pageInfo.mainInputError = true;
    ElMessage.error('预算批量规则设置有误')
    return
  }
  if (pageInfo.selectValue == 1) {//修改为
    pageInfo.multipleSelection.forEach((item) => {
      item.modifyDailyBudget = pageInfo.inputValue
    })
  }
  if (pageInfo.selectValue == 2) {//提高
    pageInfo.multipleSelection.forEach((item) => {
      item.modifyDailyBudget = parseFloat((Number(item.daily_budget) + Number(pageInfo.inputValue)).toFixed(2).toString())
    })
  }
  if (pageInfo.selectValue == 3) {//降低
    pageInfo.multipleSelection.forEach((item) => {
      item.modifyDailyBudget = parseFloat((Number(item.daily_budget) - Number(pageInfo.inputValue)).toFixed(2).toString())
    })
  }
  if (pageInfo.selectValue == 4) {//按 % 提高
    pageInfo.multipleSelection.forEach((item) => {
      item.modifyDailyBudget = parseFloat((Number(item.daily_budget) * (Number(pageInfo.inputValue) / 100 + 1)).toFixed(2).toString())
    })
  }
  if (pageInfo.selectValue == 5) {//按 % 降低
    pageInfo.multipleSelection.forEach((item) => {
      item.modifyDailyBudget = parseFloat((Number(item.daily_budget) * (1 - Number(pageInfo.inputValue) / 100)).toFixed(2).toString())
    })
  }
  if (pageInfo.selectValue == 6) {//不限
    pageInfo.multipleSelection.forEach((item) => {
      item.modifyDailyBudget = '不限'
    })
  }
  pageInfo.multipleSelection.forEach((item) => {
    item.inputError = ''
    if (item.modifyDailyBudget == '不限') return
    if (!isPositiveInteger(item.modifyDailyBudget)) {
      item.inputError = '请输入账户日预算，仅支持正整数'
      return
    }
    let isDetermine = isLimit(50, 40000000, item.modifyDailyBudget)
    if (!isDetermine.flag) {
      item.inputError = isDetermine.err
      return
    }
  })
}
// 切换显隐
const dialogShow = ref<boolean>(false)
const switchShow = (val: boolean, multipleSelection_c: any[]) => {
  dialogShow.value = val
  if (val) {
    const initObj = {
      hasBtn: false,
      cancleText: '取消',
      schedule: 1,
      successLength: 0,//修改成功条数
      multipleSelection: [],
      oldMultipleSelection: [],
      isNoLimit: false,//所选账户是否包含不限
      modifyRuleValue: 1,//规则
      inputValue: '',
      mainInputError: false,
      mainInputErrHint: '',
      selectValue: 1,
    }
    for (let key in initObj) {//所有字段 清空重来
      pageInfo[key] = _.cloneDeep(initObj[key])
    }
    pageInfo.oldMultipleSelection = multipleSelection_c;
    pageInfo.multipleSelection = _.cloneDeep(multipleSelection_c)
    pageInfo.multipleSelection.forEach((item) => {
      item['modifyDailyBudget'] = ''
      if (item.daily_budget == 0) {
        pageInfo.isNoLimit = true
      }
    });
  }
}
const selectChange = () => {
  pageInfo.inputValue = ''
  pageInfo.mainInputError = false;
  pageInfo.mainInputErrHint = ''
}
/**input change */
const onChangeInput = (type, index?) => {
  if (type == 'mainInput') {
    pageInfo.mainInputError = false;
    if (pageInfo.selectValue == 1 || pageInfo.selectValue == 2 || pageInfo.selectValue == 3) {
      if (!isPositiveInteger(pageInfo.inputValue)) {
        pageInfo.mainInputError = true;
        pageInfo.mainInputErrHint = '请输入账户日预算，仅支持正整数'
        return
      }
      let isDetermine = isLimit(1, 40000000, pageInfo.inputValue)
      if (!isDetermine.flag) {
        pageInfo.mainInputError = true;
        pageInfo.mainInputErrHint = isDetermine.err
        return
      }
    } else {
      if (!isPositiveNumberWithTwoDecimalPlaces(pageInfo.inputValue)) {
        pageInfo.mainInputError = true;
        pageInfo.mainInputErrHint = '请输入预算调整比例，最多支持小数点后两位'
        return
      }
    }
  }
  if (type == 'tableInput') {
    let item = pageInfo.multipleSelection[index]
    item.inputError = ''
    if (item.modifyDailyBudget == '') return;
    if (item.modifyDailyBudget != '不限') {
      if (!isPositiveInteger(item.modifyDailyBudget)) {
        item.inputError = '请输入账户日预算，仅支持正整数'
        return
      }
      let isDetermine = isLimit(50, 40000000, item.modifyDailyBudget)
      if (!isDetermine.flag) {
        item.inputError = isDetermine.err
        return
      }
    }
  }
}
/**使用正则表达式检查是否为正数且最多两位小数 */
const isPositiveNumberWithTwoDecimalPlaces = (value) => {
  const regex = /^[1-9]\d*(\.\d{1,2})?$|^0\.\d{1,2}$/;
  return regex.test(value.toString());
}
/**判断是否是正整数 */
const isPositiveInteger = (value) => {
  return /^[1-9]\d*$/.test(value.toString());
}
/**判断限额 */
const isLimit = (min: number, max: number, value: number) => {
  if (value < min || value > max) {
    return {
      flag: false,
      err: `日预算范围限制：${min}-${max}`
    }
  } else {
    return {
      flag: true
    }
  }
}
const tableHeaderStyle = ({ row, column, rowIndex, columnIndex }: never) => {
  return {
    backgroundColor: '#FAFAFA',
    color: '#161E46',
    height: '44px'
  }
}
// 父组件共享值
defineExpose({
  switchShow,
});
onMounted(() => {
  nextTick(() => {

  })
})
</script>
<style lang="scss" scoped>
@import "@/assets/style/batchDialogGdt.scss";

.batch-title {
  position: relative;
  margin-bottom: 25px;
  font-size: 14px;
  color: #333330;
}

.error {
  color: #f56c6c;
  line-height: 20px;
  font-size: 12px;
}

.inputError {
  --el-input-hover-border-color: #f56c6c;
  --el-input-focus-border-color: #f56c6c;
  --el-input-border-color: #f56c6c;
}

.preview-modified {
  display: flex;
  align-items: center;

  .budget {
    width: 100px;
    margin-right: 20px;
  }

  .modified-info {
    display: flex;
    align-items: center;
  }

  .status {
    width: 70px;
  }

  .text {
    color: #888;
  }

  .modified-budget {
    margin-left: 20px;
  }
}
</style>
