<template>
  <div>
    <el-card :body-style="cardBodyStyle">
      <el-form :model="query" label-position="right"  label-width="auto" >
        <el-row :gutter="10" style="margin-bottom: 5px;">
          <el-col :span="5">
            <el-form-item label="客户名称" style="margin-bottom: 0px;margin-left: 14px">
              <el-input v-model="query.tradePartnerName" placeholder="请输入客户名称" clearable>
                <template #append>
                  <el-button :icon="Search"/>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <ButtonBox @search="search"></ButtonBox>
<!--    <el-card :body-style="cardBodyStyle">-->
<!--      <el-button type="primary" @click="search" plain>查询</el-button>-->
<!--    </el-card>-->
    <el-card :body-style="cardBodyStyle">
      <el-table :data="tableData" border highlight-current-row :height="height">
        <el-table-column type="index" label="序号" align="center" width="60">
          <template #default="scope">
            <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="true" prop="tradePartnerCode" label="客户编码" header-align="center"
                         align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="tradePartnerName" label="客户名称" header-align="center" align="center"
                         show-overflow-tooltip>
        </el-table-column>

        <el-table-column v-if="true" prop="ballanceAmt" label="客户余额（元）" header-align="center" align="center"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="ballanceDtm" label="变动日期" header-align="center" align="center"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="payMth" label="收款类型" header-align="center" align="center" :formatter="formatter"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="addDeptName" label="部门" header-align="center" align="center"
                         show-overflow-tooltip>
        </el-table-column>
        <!--        <el-table-column v-if="true" prop="contrNo" label="合同编号" header-align="center" align="center"-->
        <!--                         show-overflow-tooltip>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column v-if="true" prop="khContrNo" label="对方合同编号" header-align="center" align="center"-->
        <!--                         show-overflow-tooltip>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column v-if="true" prop="capUse" label="资金用途" header-align="center" align="center"-->
        <!--                         show-overflow-tooltip>-->
        <!--        </el-table-column>-->
        <el-table-column v-if="true" prop="remark" label="备注" header-align="center" align="center"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="操作" header-align="center" align="center" width="300px">
          <template #default="scope">
            <el-button type="success" plain @click="insertDialog(scope.row)">收款分配</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-card :body-style="cardBodyStyle">
      <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="pageSizes" :total="totalRows"
                     background="background" layout="total, sizes, prev, pager, next, jumper"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange">
      </el-pagination>
    </el-card>

    <el-dialog class="diaClass" :close-on-click-modal="false" draggable title="收款分配" v-model="insertDialogShow"
               width="40%"
               top="5vh">
      <el-card class="box-card">
        <el-tag>基本信息</el-tag>
        <el-form :model="insertForm" ref="formRef" :rules="rules" label-width="130" label-position="right" :inline="true">
          <el-row>
            <el-col :span="12">
              <el-form-item label="客户名称" prop="tradePartnerName">
                <el-col :span="24">
                  <el-input v-model="insertForm.tradePartnerName" disabled>
                  </el-input>
                </el-col>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户编码" prop="tradePartnerCode">
                <el-col :span="24">
                  <el-input v-model="insertForm.tradePartnerCode" disabled>
                  </el-input>
                </el-col>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="合同编号" prop="contrNo">
                <el-input v-model="insertForm.contrNo" readonly>
                  <template #append>
                    <el-button :icon="Search" @click="dialogHt(insertForm.tradePartnerCode)"/>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="对方合同编号" >
                <el-input v-model="insertForm.khContrNo" disabled>

                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="客户余额(元)" prop="ballanceAmt">

                <el-input-number style="width: 100%" min="0" :precision="2" :step="0.1" controls-position="right"
                                 disabled
                                 v-model="insertForm.ballanceAmt"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="分配金额" prop="ballanceAmtBg">
                <el-input-number style="width: 100%" min="0" :precision="2" :step="0.1" controls-position="right"
                                 v-model="insertForm.ballanceAmtBg"></el-input-number>
<!--                <el-input style="width: 100%"-->
<!--                                 oninput="value=value.replace(/[^0-9.]/g,'')"-->
<!--                                 v-model="insertForm.ballanceAmtBg"></el-input>-->
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="款项用途" prop="invType">
                <SelectorComponent :optionList="dictList.PAY_FLAG" :value="insertForm.invType" :allowSelect="invTypeDisabled"
                                   @change="invTypeDic"/>

              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="备注">
                <el-input
                    v-model="insertForm.remark"
                    :autosize="{ minRows: 2, maxRows: 4 }"
                    type="textarea"
                    placeholder=""
                />
              </el-form-item>
            </el-col>
          </el-row>

        </el-form>
      </el-card>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" plain @click="insertDialogSave(formRef)" :loading="saveLoading">保存</el-button>
          <el-button type="danger" plain @click="insertDialogShow = false">取消</el-button>
        </div>
      </template>


    </el-dialog>
    <PopupCot ref="PopupRefHT" :params="contrTyStr" @receive-from-child="retu"></PopupCot>

  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  onMounted,
  getCurrentInstance
} from 'vue'
import {Search} from '@element-plus/icons-vue'

const {
  proxy
} = getCurrentInstance()


import style from '@/tools/style'

const cardBodyStyle = ref(style.card)
import SearchBar from '@/components/SearchBar.vue';

import PopupMenuTree from '@/components/PopupMenuTree.vue'
import ButtonBar from "@/components/ButtonBar.vue";
import Popup_base_ht from "@/views/cot/components/Popup_base_ht.vue";
import PopupCot from "@/views/cot/components/PopupCot.vue";
import SelectorComponent from "@/views/sal/components/Selector_component.vue";
import ButtonBox from "@/components/ButtonBox.vue";

const searchBarRef = ref(null)
const formItem = ref([
  {
    prop: 'birthDate',
    type: 'input',
    label: '订单号'
  },
  {
    prop: 'age',
    type: 'input',
    label: '客户名称',
    searchButton: true,
    searchCallback: 'showPop'
  }
])

const contrTyStr = ref({
  contrTy: '10',
  supplierCd:''
})
const formRef = ref(null)

const searchForm = (val) => {
  query.value = searchBarRef.value.form
  console.log(JSON.stringify(query.value))
}

/**
 *   查询
 */

const query = ref({
  tradePartnerName: '',

})
const tableData = ref([])
const tableDataTwo = ref([])

const handleSearch = (val) => {
  query.value = searchBarRef.value.form
  console.log(JSON.stringify(query.value))
  currentPage.value = 1
  getTableData()
}
const getTableData = () => {
  var url = 'sal/PaymentBallance/query'
  var param = {
    page: currentPage.value,
    rows: pageSize.value,
    params: JSON.stringify(query.value)
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      tableData.value = response.data.data.records
      totalRows.value = response.data.data.total
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}
/**
 *   查询
 */
/**
 * 分页
 */
const currentPage = ref(1)
const totalRows = ref(0)
const pageSizes = ref([10, 20, 30, 40])
const pageSize = ref(10)
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  getTableData()
}
/**
 * 分页
 */


const PopupMenuTreeRef = ref(null)
const showPop = () => {
  console.log('showPop')
  PopupMenuTreeRef.value.show()
}
/**
 * 新增表单form
 */
const insertForm = ref({
  id: '',
  contrNo: '',
  ordTy: '',
  supplierNm: '',
  ballanceAmtBg: 0,
  capUse:'',
  remark: '',
  khContrNo: '',
  ballanceAmt: '',
  invType: '',
})

// 新增订单
const insertDialogShow = ref(false)
const insertDialog = (row) => {
  insertForm.value = {
    id: '',
    contrNo: '',
    ordTy: '',
    supplierNm: '',
    ballanceAmtBg: 0,
    capUse:'',
    remark: '',
    khContrNo: '',
    ballanceAmt: '',
    invType: '',
  }
  saveLoading.value = false
  invTypeDisabled.value = true
  var url = 'sal/PaymentBallance/queryByPK'
  var param = {
    id: row.id
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      insertForm.value = response.data.data
      insertForm.value.ballanceAmtBg =  0

    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
  insertDialogShow.value = true
}
const handleEdit = () => {
  insertDialogShow.value = true
}
const handleDelete = (row) => {
  ElMessageBox.confirm(
      '确定删除本条记录?',
      '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
      }
  )
      .then(() => {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消',
        })
      })
}

const insertDialogSave = (formRef) => {
  if (!formRef) return
  formRef.validate((valid) => {
    if (valid) {
      saveLoading.value = true
      console.log('submit!')
      var url = 'sal/PaymentBallance/saveBallanceAndRecords'
      var param = {
        json: JSON.stringify(insertForm.value),

      }
      proxy.$axios.get(url, param).then(response => {
        if (response.data.code == 0) {
          ElMessage({
            message: '保存成功',
            type: 'success',
          })
          insertDialogShow.value = false
          search()
        } else {
          ElMessage({
            type: 'error',
            message: '操作失败' + response.data.msg
          })
        }
        saveLoading.value = false
      });
    } else {
      console.log('error submit!')
      return false
    }
  })
  console.log("insertForm.value", insertForm.value)

}

const validateOrderPayTypes = (rule, value, callback) =>{
  if(!value ) { // 自定义验证条件，返回错误提示文字
    if (value === 0  || value === '0'){
      callback(new Error('不允许为0'))
    }
    callback(new Error('不允许为空,不允许为0'))
  } else {
    if (value > Number(insertForm.value.ballanceAmt)){
      callback(new Error('收款分配金额不允许大于客户余额'))
    }
    if (value == 0){
      callback(new Error('金额不允许为0'))
    }
    if (value < 0){
      callback(new Error('金额不允许为负数'))
    }
    var sp = String(value).split('.')
    if (sp.length > 1 ){
      if (sp[1].length >2){
        callback(new Error('金额必须为整数或者2位小数'))
      }
    }
    callback()
  }
}

// 校验
const rules = ref({
  contrNo: [
    {required: true, message: '不允许为空', trigger: 'change'},
  ],
  salOrdNo: [
    {required: true, message: '不允许为空', trigger: 'blur'},
  ],
  capUse: [
    {required: true, message: '不允许为空', trigger: 'blur'},
  ],
  ballanceAmtBg: [
    {required: true,validator: validateOrderPayTypes,  trigger: 'change' |'blur'},
  ],
  invType: [
    {required: true, message: '不允许为空', trigger: 'change'},
  ],
})

const otherQuery = () => {

}
const search = () => {
  getTableData()
}
const PopupRefHT = ref(null)
const dialogHt = (val) => {
  contrTyStr.value.supplierCd = val
  PopupRefHT.value.open()
}
const invTypeDisabled = ref(true)

const retu = (val) => {
  console.log(val)
  insertForm.value.contrNo = val.contrNo
  insertForm.value.khContrNo = val.khContrNo
  // 查询当前合同下的  收付款方式
  invType(val.contrNo)
  invTypeDisabled.value = false
}
const invTypeList = ref([])
const invType = (val) => {
  document.getElementById("invType")
  var url = 'cot/Invtype/queryAll'
  var obj = {
    contrCd :val
  }
  var param = {
    params: JSON.stringify(obj),

  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == 0) {
      var ss = []
      var count = 0
      dictList.value.PAY_FLAG.forEach((item) => {
        item.disabled = true
        response.data.data.records.forEach((inx) => {
          if (item.dicCode == inx.payFlag || item.dicName == inx.payFlag){
            item.disabled = false
            if (count == 0){
              count ++;
              insertForm.value.invType = inx.payFlag
            }

            return
          }
        })
      })

      // response.data.data.records.forEach((item) => {
      //   ss.push({dicCode: item.payFlag,dicName: item.payFlag, id: item.id})
      // })
      // invTypeList.value = ss
    } else {
      ElMessage({
        type: 'error',
        message: '操作失败' + response.data.msg
      })
    }
  });
}
const invTypeDic = (val) =>{
  insertForm.value.invType = val
}
const dictList = ref({})
const dictData = () => {
  var url = 'framework/Common/querySelectorList'
  var param = {
    type: JSON.stringify(['PAY_FLAG' , 'COM_PAY_MTH'])
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      dictList.value = response.data.data
      dictList.value.PAY_FLAG[0].disabled = false
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}
const saveLoading = ref(false)

const height = ref(600)
const updateViewportHeight = () => {
  height.value = window.innerHeight * 0.65
  console.log( window.innerHeight);
};

const formatter = (row, column, cellValue, index) => {
  if (!cellValue || cellValue == null || cellValue == '') {
    return cellValue
  }
  switch (column.property) {
    case 'payMth':
      cellValue = dictList.value && Array.isArray(dictList.value.COM_PAY_MTH)
          ? dictList.value.COM_PAY_MTH.find(item => item.dicCode == cellValue)?.dicName
          : undefined
      break;
  }
  return cellValue
}

onMounted(() => {
  getTableData()
  dictData()
  updateViewportHeight()
  console.log(`the component is now mounted.`)
})
</script>

<style scoped>
::v-deep .diaClass .el-form-item {
  width: 100%
}

::v-deep .el-dialog__body {
  background-color: #F2F6FC;
}

.el-date-editor--date {
  width: 100%;
}
</style>
