<template>
  <div>
    <div>
      <el-row>
        <el-col :span="24">
          <el-form :model="queryParams" ref="queryRef" :inline="true">
            <el-form-item label="转介人姓名" prop="broker">
              <el-input
                v-model="queryParams.broker"
                placeholder="请输入转介人姓名"
                clearable
                @clear="resetQuery"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="Search" @click="getTableList">查询</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-col>

        <el-col :span="24" style="margin-bottom: 10px" v-if="props.policyNo">
          <el-button type="primary" icon="Plus" @click="getGenerate">生成预计发佣</el-button>
          <el-button type="warning" @click="getOperationData">生成发佣日志信息</el-button>
        </el-col>
        <el-table :data="tableList" border @sort-change="sortChange">
          <el-table-column label="转介人" prop="broker" align="center" width="180" fixed="left">
          </el-table-column>
          <el-table-column
            label="发佣名称"
            prop="fortuneName"
            align="center"
            width="180"
          ></el-table-column>
          <el-table-column
            label="发佣类型"
            prop="fortuneType"
            align="center"
            width="180"
          ></el-table-column>
          <el-table-column
            label="发佣金额"
            prop="amount"
            align="center"
            width="180"
          ></el-table-column>
          <el-table-column label="发佣币种" prop="currency" align="center" width="160">
            <template #default="scope">
              <dict-tag :options="fetchDictData('bx_currency_type')" :value="scope.row.currency" />
            </template>
          </el-table-column>
          <el-table-column
            label="团队名称"
            prop="team"
            align="center"
            width="180"
          ></el-table-column>
          <el-table-column label="发佣期数" prop="fortunePeriod" align="center" width="180">
            <template #default="scope">
              {{ scope.row.fortunePeriod ? `第${scope.row.fortunePeriod}年` : '--' }}
            </template>
          </el-table-column>
          <el-table-column label="发佣总期数" prop="fortuneTotalPeriod" align="center" width="180">
            <template #default="scope">
              {{ scope.row.fortuneTotalPeriod ? `${scope.row.fortuneTotalPeriod}年` : '--' }}
            </template>
          </el-table-column>
        </el-table>

        <el-col :span="24">
          <pagination
            v-show="total >= 0"
            :total="total"
            v-model:page="queryParams.pageNo"
            v-model:limit="queryParams.pageSize"
            @pagination="getTableList"
          />
        </el-col>
        <!-- <el-col :span="24" align="center" style="margin-top: 10px">
          <el-button type="success" size="large" @click="submitTable">提交</el-button>
        </el-col> -->
      </el-row>
      <el-dialog :title="commissionTitle" v-model="editCommission" width="800px" append-to-body>
        <el-table :data="operationList" border>
          <el-table-column label="保单号" prop="policyNo" align="center" width="180" fixed="left">
          </el-table-column>
          <el-table-column label="状态" prop="status" align="center" width="180">
            <template #default="scope">
              <dict-tag :options="tagStatus" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column
            label="发佣日志信息"
            prop="errorMsg"
            align="center"
            width="180"
          ></el-table-column>

          <el-table-column prop="createTime" label="日志时间" align="center">
            <template #default="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="operationPages.total >= 0"
          :total="operationPages.total"
          v-model:page="operationPages.pageNo"
          v-model:limit="operationPages.pageSize"
          @pagination="getOperationData"
        />
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="closeDialog">关 闭</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script setup name="policyInfo">
import useDictStore from '@/store/modules/dict'
import { watch } from 'vue'

import { getAllCompanys } from '@/api/common'
import {
  getExpectedFortuneList,
  editSigalCommission,
  editMultipleCommission,
  delCommissionExpected,
  getExpectedFortuneLog,
  expectedFortuneGenerate
} from '@/api/sign/underwritingMain'
import useUserStore from '@/store/modules/user'
const userStore = useUserStore()
const dictStore = useDictStore() //获取字典数据
const props = defineProps({
  activeName: { type: String, default: '' }, //tab名称
  policyBizId: { type: String, default: '' }, //提交状态，新增、修改
  policyNo: { type: String, default: '' }, //提交状态，新增、修改
  dictTypeLists: { type: Array, default: () => [] } //多个字典值数据
})

const emit = defineEmits(['handleSuccess'])
const { proxy } = getCurrentInstance()

const loading = ref(false)
const editStatus = ref(false) // 表单是否可编辑,若是修改初始不可编辑
const searchOptions = ref({}) // 存储不同key对应的选项
const searchLoadingStates = ref({}) // 存储不同key对应的加载状态
const total = ref(0)
const oldTotal = ref(0)
const tableList = ref([])
const isEditing = ref(false)
const commissionTitle = ref('生成发佣日志信息')
const editCommission = ref(false)
const isClickGenerate = ref(false)
const operationList = ref([])
const tagStatus = ref([
  { label: '失败', value: '1', elTagType: 'danger' },
  { label: '进行中', value: '2', elTagType: 'warning' },
  { label: '成功', value: '0', elTagType: 'success' }
])
const operationPages = ref({
  pageNo: 1,
  pageSize: 5,
  total: 0
})
const data = reactive({
  form: {},
  queryParams: {
    pageNo: 1,
    pageSize: 10,
    // sortField: 'commissionPeriod',
    // sortOrder: 'ascend',
    policyNo: props.policyNo || ''
  }
})
const { queryParams, form } = toRefs(data)
const closeDialog = () => {
  editCommission.value = false
  operationList.value = []
  operationPages.value = {
    pageNo: 1,
    pageSize: 5,
    total: 0
  }
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  queryParams.value = {
    pageNo: 1,
    pageSize: 10,
    policyNo: props.policyNo || ''
  }
  getTableList()
}
const sortChange = ({ prop, order }) => {
  if (isEditing.value) {
    return // 编辑期间不进行排序
  }
  if (order == 'ascending') {
    queryParams.value.sortOrder = 'ascend'
  } else {
    queryParams.value.sortOrder = 'descend'
  }
  if (prop) {
    queryParams.value.sortField = prop
  }
  // 重新获取表格数据
  getTableList()
}
// 搜索方法
const searchSelectList = async (query, fieldKey) => {
  // 设置该字段的加载状态
  searchLoadingStates.value[fieldKey] = true

  try {
    // 根据不同的字段key调用不同的API
    if (fieldKey === 'reconciliationCompany') {
      const params = {
        deptName: query.trim(),
        pageNo: 1,
        pageSize: 10
      }
      getAllCompanys(params).then(response => {
        response.data.records = response.data.records.map(item => {
          return {
            ...item,
            label: item.deptName,
            value: item.deptBizId
          }
        })
        searchOptions.value[fieldKey] = response.data.records
      })
    }
  } catch (error) {
    console.error(`${fieldKey} 搜索失败`, error)
    searchOptions.value[fieldKey] = []
  } finally {
    searchLoadingStates.value[fieldKey] = false
  }
}

// 获取字典数据
const fetchDictData = dictType => {
  let options = []
  try {
    dictStore.dictTypeLists.forEach(item => {
      if (item.dictType == dictType) {
        options = item.dictItemList
      }
    })
    return options
  } catch (error) {
    console.error('获取字典数据失败:', error)
    return []
  }
}

// 是否生成发佣数据
const getOperationData = () => {
  let data = {
    pageNo: operationPages.value.pageNo,
    pageSize: operationPages.value.pageSize,
    policyNo: props.policyNo
  }
  getExpectedFortuneLog(data).then(res => {
    if (res.code == 200) {
      operationList.value = res.data.records
      operationPages.value.total = res.data.total
      editCommission.value = true
    } else {
      proxy.$message.error(res.msg)
    }
  })
}
const getGenerate = () => {
  expectedFortuneGenerate({ policyNo: props.policyNo }).then(res => {
    isClickGenerate.value = true //代表之前已经点击过生成发佣按钮
    if (res.code == 200) {
      proxy.$message.success(res.msg)
    } else {
      proxy.$message.error(res.msg)
    }
  })
}
// 处理单个提交
const handleUpdate = row => {
  let obj = JSON.parse(JSON.stringify(row))
  if (obj.commissionDate) {
    obj.commissionDate = proxy.formatToDate(obj.commissionDate)
  }
  if (obj.commissionName) {
    obj.commissionType = obj.commissionName
  }
  dictStore.insureCompanyList.forEach(item => {
    if (obj.reconciliationCompany && obj.reconciliationCompany == item.value) {
      obj.reconciliationCompany = item.label
      obj.reconciliationCompanyBizId = item.value
    }
  })
  editSigalCommission(obj).then(res => {
    if (res.code == 200) {
      proxy.$message.success('提交成功')
      getTableList()
    }
  })
}
const submitTable = () => {
  if (tableList.value.length == 0) {
    proxy.$message.warning('请先添加来佣')
    return
  }
  let result = JSON.parse(JSON.stringify(tableList.value))
  result.forEach(item => {
    if (item.commissionDate) {
      item.commissionDate = proxy.formatToDate(item.commissionDate)
    }
    if (item.commissionName) {
      item.commissionType = item.commissionName
    }
    dictStore.insureCompanyList.forEach(item1 => {
      if (item.reconciliationCompany && item.reconciliationCompany == item1.value) {
        item.reconciliationCompany = item1.label
        item.reconciliationCompanyBizId = item1.value
      }
    })
  })
  editMultipleCommission({ commissionExpectedAddDtoList: result }).then(res => {
    if (res.code == 200) {
      proxy.$message.success('提交成功')
      getTableList()
    }
  })
}
const handleDetele = (row, index) => {
  if (row.commissionExpectedBizId) {
    proxy.$modal
      .confirm('是否确认删除此来佣？')
      .then(function () {
        return delCommissionExpected(row.commissionExpectedBizId)
      })
      .then(res => {
        if (res.code == 200) {
          proxy.$modal.msgSuccess('删除成功')
          getTableList()
        }
      })
      .catch(() => {})
  } else {
    tableList.value.splice(index, 1)
    if (total.value > 0) {
      total.value = total.value - 1
    } else {
      total.value = 0
    }

    proxy.$modal.msgSuccess('删除成功')
  }
}
const getTableList = () => {
  loading.value = true
  try {
    getExpectedFortuneList(queryParams.value).then(response => {
      if (response.code == 200) {
        total.value = oldTotal.value = response.data.total
        tableList.value = response.data.records
        loading.value = false
        if (isClickGenerate.value && tableList.value.length == 0) {
          proxy.$message.warning('暂无发佣数据，请查看生成发佣日志信息')
        }
      }
    })
  } catch (error) {
    tableList.value = []
  } finally {
    loading.value = false
  }
}
watch(
  () => props.activeName,
  newVal => {
    if (newVal === 'expectedFortune') {
      searchOptions.value['reconciliationCompany'] = dictStore.insureCompanyList
      getTableList()
    }
  }
)
</script>
<style lang="scss" scoped>
.domEmpty {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  font-size: 16px;
  color: #a8abb2;
  margin-top: 100px;
}
.topBtn {
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}
.deleteIcon {
  color: red;
  font-size: 18px;
  padding-top: 10px;
}
.formBox {
  width: 100%;
  .fatherLable {
    font-size: 18px;
    border-left: 4px solid #165dff;
    padding-left: 5px;
    margin-bottom: 5px;
  }
  .subTitle {
    font-size: 15px;
    /* padding-left: 8px; */
    margin-bottom: 10px;
  }
  .childLabel {
    font-size: 14px;
    /* padding-left: 15px; */
    margin-bottom: 15px;
  }
  .fatherDes {
    font-size: 14px;
    color: #a8abb2;
    margin-top: 5px;
    margin-bottom: 20px;
  }
  .inputBox {
    width: 100%;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    min-height: 32px;
    padding: 0px 11px;
    .rightArrow {
      font-size: 14px;
      color: #a8abb2;
    }
  }
}
.tabButton {
  /* box-shadow: 0 -1px 14px #00000014; */
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding-top: 20px;
  .sumbitBtn {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    height: 60px;
    background-color: #165dff;
    color: #fff;
    padding: 0 30px;
    .buttonIcon {
      font-size: 16px;
      color: #fff;
    }
  }
}
.customerBox {
  .customerItem {
    padding: 10px;
    border-radius: 5px;
    margin-bottom: 20px;
    box-shadow: 0 -1px 14px #00000014;
    .top {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      .left {
        width: 40%;
        display: flex;
        align-items: center;
        justify-content: flex-start;
        .gender {
          display: flex;
          align-items: center;
        }
      }
    }
    .bottom {
      .infoItem {
        display: flex;
        align-items: center;
        margin: 5px 0;
      }
    }
  }
  .customerItem:last-child {
    margin-bottom: 0px;
  }
}
/* 新增的样式：防止label换行并显示省略号 */
.formFna :deep(.el-checkbox) {
  margin-right: 10px;
}

@media only screen and (min-width: 768px) {
  .formInput {
    margin-top: 30px !important;
  }
}

@media only screen and (min-width: 1200px) {
  .formInput {
    margin-top: 30px !important;
  }
}
</style>
