<template>
  <div class="page-container column-container">
    <el-form class="list-search-container" :model="form" ref="queryRef" :inline="true">
      <el-form-item label="外协结算月设置">
      </el-form-item>
      <el-form-item label="开始日期：" style="margin-left: 50px;">
        <el-date-picker v-model="form.startDate" type="date" value-format="YYYY-MM-DD" :editable="false"
          :clearable="false" placeholder="结算日期" style="width: 130px" @change="handleDateChange"
          :disabled-date="(arg) => disabledDateHandler(arg, 'startDate')" />
      </el-form-item>
      <el-form-item label="结束日期：">
        <el-date-picker v-model="form.endDate" type="date" value-format="YYYY-MM-DD" :editable="false"
          :clearable="false" placeholder="结束日期" style="width: 130px" @change="handleDateChange"
          :disabled-date="(arg) => disabledDateHandler(arg, 'endDate')" />
      </el-form-item>
      <el-form-item style="margin-left: 200px;">
        <el-button type="primary" @click="setMonth">设置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref } from 'vue'
const { proxy } = getCurrentInstance();
import { listOutsourceBalanceMonth, saveOutsourceBalanceMonth } from '@/api/business/outsourceBalanceMonth.js'

const form = ref({
  startDate: null,
  endDate: null
})

const getList = () => {
  listOutsourceBalanceMonth({}).then(res => {
    if (res.rows.length > 0) {
      form.value.startDate = res.rows.length > 0 ? res.rows[0].startDate : ''
      form.value.endDate = res.rows.length > 0 ? res.rows[0].endDate : ''
    } else {
      form.value = {
        startDate: null,
        endDate: null
      }
    }
  })
}
const setMonth = () => {
  if (form.value.startDate == null || form.value.endDate == null) {
    proxy.$modal.msgError('请选择开始日期和结束日期')
    return
  }
  proxy.$confirm('确定要设置外协结算月吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(res => {
    saveOutsourceBalanceMonth(form.value).then(res => {
      if (res.code === 200) {
        proxy.$modal.msgSuccess('设置成功')
        getList()
      }
    })
  }).catch(_ => {
    proxy.$modal.msgError('取消设置')
  })
}

const handleDateChange = () => {
  console.log(form.value.startDate, form.value.endDate)
}


function disabledDateHandler(date, field) {
  if (field === 'startDate') {
    if (form.value.endDate != null && date >= proxy.moment(form.value.endDate)) return true
    else return false
  } else if (field === 'endDate') {
    if (form.value.startDate != null && date <= proxy.moment(form.value.startDate)) return true
    else return false
  }
}

getList()
</script>