<template>
  <view>
    <CuNavbar :isBack="isBack" title="上报"></CuNavbar>
    <view
      :class="[
        checkPermission(['store']) && form.allow_rereport
          ? ''
          : 'pointer-events-none',
      ]"
    >
      <uv-form
        class="mt-30rpx"
        labelPosition="left"
        ref="formRef"
        :model="form"
        :rules="rules"
        errorType="toast"
        labelWidth="130rpx"
      >
        <view class="px-base space-y-20rpx">
          <view class="card">
            <view class="pl-20rpx">
              <uv-form-item
                label="日期"
                prop="form.date"
                @click="showDateSelect"
              >
                <uv-input
                  disabled
                  v-model="form.date"
                  disabledColor="#ffffff"
                  placeholder="请选择日期"
                  :border="`none`"
                >
                </uv-input>
                <template v-slot:right>
                  <uv-icon name="arrow-right"></uv-icon>
                </template>
              </uv-form-item>
            </view>
          </view>
          <view class="card" v-for="(item, i) in form.items" :key="i">
            <TitleComp :title="item.name"></TitleComp>
            <view class="mt-20rpx">
              <uv-line color="#f5f5f5"></uv-line>
            </view>
            <view class="pl-20rpx">
              <uv-form-item label="销售" :prop="`items.${i}.sales`">
                <uv-input
                  @input="salesChange"
                  v-model="item.sales"
                  :border="`none`"
                  type="digit"
                  :placeholder="`请输入${item.name}销售金额`"
                ></uv-input>
              </uv-form-item>
              <uv-line color="#f5f5f5"></uv-line>
              <uv-form-item label="兑奖" :prop="`items.${i}.expenditure`">
                <uv-input
                  @input="expenditureChange"
                  v-model="item.expenditure"
                  :border="`none`"
                  type="digit"
                  :placeholder="`请输入${item.name}兑奖金额`"
                ></uv-input>
              </uv-form-item>
            </view>
          </view>
          <view class="card">
            <TitleComp title="汇总情况"></TitleComp>
            <view class="mt-20rpx">
              <uv-line color="#f5f5f5"></uv-line>
            </view>
            <view class="pl-20rpx">
              <uv-form-item label="销售合计" prop="sales">
                <uv-input
                  :border="`none`"
                  type="digit"
                  v-model="form.sales"
                  placeholder="请输入总账销售金额"
                ></uv-input>
              </uv-form-item>
              <uv-line color="#f5f5f5"></uv-line>
              <uv-form-item label="兑奖合计" prop="expenditure">
                <uv-input
                  type="digit"
                  :border="`none`"
                  v-model="form.expenditure"
                  placeholder="请输入电总账兑奖金额"
                ></uv-input>
              </uv-form-item>
              <uv-line color="#f5f5f5"></uv-line>
              <uv-form-item label="新增客户" prop="new_customers">
                <uv-input
                  :border="`none`"
                  v-model="form.new_customers"
                  type="number"
                  placeholder="请输入微信新增人数"
                ></uv-input>
              </uv-form-item>
              <uv-line color="#f5f5f5"></uv-line>
              <uv-form-item label="交账金额" prop="handover_amount">
                <uv-input
                  :border="`none`"
                  type="digit"
                  v-model="form.handover_amount"
                  placeholder="请输入交账金额"
                ></uv-input>
              </uv-form-item>
              <view class="text-primary text-24rpx py-10rpx"
                >* 请确保填写的交账金额正确无误！</view
              >
            </view>
          </view>
          <view class="card">
            <TitleComp title="时段报表照片">
              <template #right>
                <view class="text-24rpx text-gray-400"
                  >{{ form.photos.length }}/9</view
                >
              </template>
            </TitleComp>
            <uv-form-item label="" prop="photos">
              <view>
                <uv-upload
                  width="200rpx"
                  height="200rpx"
                  :maxCount="9"
                  multiple
                  :fileList="form.photos"
                  @afterRead="afterRead"
                  @delete="deletePic"
                  name="photos"
                ></uv-upload>
              </view>
            </uv-form-item>
            <view class="text-primary text-24rpx py-10rpx">
              *竞彩时段报表照片，玩法时段报表照片，每日账本上传（需亲笔签字），销量本上传
            </view>
          </view>
        </view>
      </uv-form>
    </view>
    <view class="h-130rpx">
      <view
        class="fixed bottom-0 left-0 right-0 h-120rpx bg-white flex-center box-border px-base"
        :style="style"
      >
        <view class="w-full">
          <uv-button
            :disabled="!form.allow_rereport"
            type="primary"
            shape="circle"
            block
            @click="submit"
          >
            上报
          </uv-button>
        </view>
      </view>
    </view>

    <uv-calendars
      color="#ee2c37"
      confirmColor="#ee2c37"
      ref="calendars"
      @confirm="calendarsConfirm"
      :endDate="endDate"
      :date="form.date"
    />

    <uv-modal
      ref="modalRef"
      title="提示"
      content="确定提交？"
      @confirm="onSubmit"
      :showCancelButton="true"
    ></uv-modal>
  </view>
</template>

<script setup>
import { http } from '@/utils/request'
import CuNavbar from '@/components/cu-navbar/index'
import TitleComp from '@/components/title-comp/index'
import { addUnit, sys } from '@climblee/uv-ui/libs/function/index'
import { computed, ref, onBeforeMount, reactive, onMounted, watch } from 'vue'
import { useUserStore } from '@/store/modules/user'
import { timeFormat } from '@climblee/uv-ui/libs/function/index'
import { add } from '@/utils/index'
import checkPermission from '@/utils/permission'
import { onShow } from '@dcloudio/uni-app'
const calendars = ref(null)
const modalRef = ref(null)
const formRef = ref(null)
const userStore = useUserStore()

const userInfo = computed(() => userStore.userInfo || {})
const store = computed(() => userInfo.value.store)
const endDate = timeFormat(new Date(), 'yyyy-mm-dd')

const form = reactive({
  date: endDate,
  items: [],
  new_customers: '',
  sales: '',
  expenditure: '',
  handover_amount: '',
  photos: [],
})
const rules = reactive({
  date: {
    required: true,
    message: '请选择日期',
    trigger: ['change'],
  },
  handover_amount: {
    required: true,
    message: '请输入交账金额',
    trigger: ['change'],
  },
  photos: {
    type: 'array',
    required: true,
    message: '请上传时段报表照片',
  },
})

const props = defineProps({
  isBack: {
    type: Boolean,
    default: false,
  },
})
const style = computed(() => {
  const style = {}
  style.bottom = addUnit(sys().windowBottom, 'px')
  return style
})

onShow(() => {
  getData(endDate)
})

const submit = () => {
  formRef.value.validate().then((res) => {
    modalRef.value.open()
  })
}

const onSubmit = async () => {
  const params = {
    date: form.date,
    sales: form.sales,
    expenditure: form.expenditure,
    handover_amount: form.handover_amount,
    new_customers: form.new_customers,
    photos: form.photos.map((item) => item.url),
    items: form.items,
  }
  http
    .request({
      url: '/ledgers',
      method: 'POST',
      header: {
        Accept: 'application/json',
      },
      data: params,
    })
    .then((res) => {
      uni.$emit('revert:submit', res)
      getData()
      uni.showToast({
        title: '提交成功',
        duration: 2000,
        icon: 'none',
      })
    })
}

const getData = async () => {
  const resData = await http.get(`/ledgers/${form.date}`)

  Object.assign(form, resData, {
    photos:
      resData?.photos?.map((item) => {
        return { url: item }
      }) || [],
  })
}

const getTypeList = () => {
  http
    .get('/keywords', {
      params: {
        parent_key: 'lottery_type',
      },
    })
    .then((res) => {
      form.items = res
      res.forEach((item, i) => {
        rules[`items.${i}.${'sales'}`] = {
          required: true,
          message: `请输入${item.name}销售金额`,
        }
        rules[`items.${i}.${'expenditure'}`] = {
          required: true,
          message: `请输入${item.name}兑奖金额`,
        }
      })
      console.log(rules)
    })
}

const calendarsConfirm = (e) => {
  form.date = e.fulldate
  getData()
}

const showDateSelect = () => {
  calendars.value.open()
  hideKeyboard()
}

const hideKeyboard = () => {
  uni.hideKeyboard()
}

const afterRead = async (event) => {
  let lists = [].concat(event.file)
  let fileListLen = form[event.name].length

  lists.map((item) => {
    form[event.name].push({
      ...item,
      status: 'uploading',
      message: '上传中',
    })
  })
  for (let i = 0; i < lists.length; i++) {
    const result = await uploadFilePromise(lists[i].url)
    let item = form[event.name][fileListLen]
    form[event.name].splice(
      fileListLen,
      1,
      Object.assign(item, {
        status: 'success',
        message: '',
        url: result,
      })
    )
    fileListLen++
  }
}

const uploadFilePromise = (url) => {
  return new Promise((resolve, reject) => {
    http
      .upload('/fileupload', {
        filePath: url,
        name: 'file',
      })
      .then((res) => {
        resolve(res.url)
      })
      .catch((err) => {
        reject(err)
      })
  })
}

const deletePic = (event) => {
  form[event.name].splice(event.index, 1)
}

const salesChange = () => {
  const val = form?.items || []
  const sales = val.reduce((a, b) => {
    return add(a, b?.sales ?? 0)
  }, 0)
  form.sales = sales || null
}

const expenditureChange = () => {
  const val = form?.items || []
  const expenditure = val.reduce((a, b) => {
    return add(a, b?.expenditure ?? 0)
  }, 0)
  form.expenditure = expenditure || null
}

watch(
  () => form.items,
  (val) => {
    const sales = val.reduce((a, b) => {
      return add(a, b?.sales ?? 0)
    }, 0)
    const expenditure = val.reduce((a, b) => {
      return add(a, b?.expenditure ?? 0)
    }, 0)
    // form.sales = sales || null
    // form.expenditure = expenditure || null
  },
  {
    immediate: true,
    deep: true,
  }
)
</script>
