<template>
  <div>
    <div>
      <el-row>
        <el-col :span="24" style="display: flex; justify-content: flex-start; margin-bottom: 10px">
          <el-button style="margin-top: 10px" type="primary" icon="Plus" @click="addChildren"
            >添加</el-button
          >
        </el-col>
        <el-table :data="tableList" border @sort-change="sortChange">
          <el-table-column type="index" width="60" label="序号" />
          <!-- <el-table-column label="保单号" prop="policyNo" align="center" width="120">
            <template #default="scope">
              <el-input
                v-model="scope.row.policyNo"
                size="default"
                type="text"
                placeholder="请输入"
              />
            </template>
          </el-table-column> -->
          <el-table-column label="来佣名称" prop="commissionName" align="center" width="180">
            <template #default="scope">
              <el-input
                v-model="scope.row.commissionName"
                size="default"
                type="text"
                placeholder="请输入"
              />
            </template>
          </el-table-column>
          <!-- sortable -->
          <el-table-column label="来佣金额" prop="amount" align="center" width="120">
            <template #default="scope">
              <el-input
                v-model="scope.row.amount"
                size="default"
                type="number"
                placeholder="请输入"
              />
            </template>
          </el-table-column>
          <!-- sortable -->
          <el-table-column label="佣金期数" prop="commissionPeriod" align="center" width="120">
            <template #default="scope">
              <el-input
                v-model="scope.row.commissionPeriod"
                size="default"
                type="number"
                placeholder="请输入"
              />
            </template>
          </el-table-column>
          <el-table-column label="预计来佣日期" prop="commissionDate" align="center" width="150">
            <template #default="scope">
              <el-date-picker
                style="width: 100%"
                v-model="scope.row.commissionDate"
                type="date"
                placeholder="请输入"
              />
            </template>
          </el-table-column>
          <el-table-column label="来佣币种" prop="currency" align="center" width="160">
            <template #default="scope">
              <el-select v-model="scope.row.currency" placeholder="请选择">
                <el-option
                  v-for="item in fetchDictData('bx_currency_type')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <!-- sortable -->
          <el-table-column label="对账公司" prop="reconciliationCompany" align="center" width="150">
            <template #default="scope">
              <el-select
                v-model="scope.row.reconciliationCompany"
                filterable
                remote
                reserve-keyword
                placeholder="请输入关键词搜索"
                :remote-method="query => searchSelectList(query, 'reconciliationCompany')"
                :loading="searchLoadingStates['reconciliationCompany']"
              >
                <el-option
                  v-for="item in searchOptions['reconciliationCompany'] || []"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>

          <el-table-column label="总来佣期数" prop="totalPeriod" align="center">
            <template #default="scope">
              <el-input
                v-model="scope.row.totalPeriod"
                size="default"
                type="number"
                placeholder="请输入"
              />
            </template>
          </el-table-column>

          <el-table-column label="备注" prop="remark" align="center" width="150">
            <template #default="scope">
              <el-input
                v-model="scope.row.remark"
                size="default"
                type="textarea"
                placeholder="请输入"
              />
            </template>
          </el-table-column>
          <el-table-column width="120px" align="center" label="操作" fixed="right">
            <template #default="scope">
              <el-button
                v-if="scope.row.commissionExpectedBizId"
                type="primary"
                link
                @click="handleUpdate(scope.row)"
                >修改</el-button
              >
              <el-button type="danger" link @click="handleDetele(scope.row, scope.$index)"
                >删除</el-button
              >
            </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>
        <div>
          <el-form>
            <el-row :gutter="30">
              <el-col :span="12">
                <el-form-item label="来佣名称" prop="commissionName" label-position="top">
                  <el-input
                    v-model="form.commissionName"
                    size="default"
                    type="text"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="来佣金额" prop="amount" label-position="top">
                  <el-input
                    v-model="form.amount"
                    size="default"
                    type="number"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="预计来佣日期" prop="commissionDate" label-position="top">
                  <el-date-picker
                    style="width: 100%"
                    v-model="form.commissionDate"
                    type="date"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="佣金期数" prop="commissionPeriod" label-position="top">
                  <el-input
                    v-model="form.commissionPeriod"
                    size="default"
                    type="number"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="来佣币种" prop="currency" label-position="top">
                  <el-select v-model="form.currency" placeholder="请选择">
                    <el-option
                      v-for="item in fetchDictData('bx_currency_type')"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="对账公司" prop="reconciliationCompany" label-position="top">
                  <el-select
                    v-model="form.reconciliationCompany"
                    filterable
                    remote
                    reserve-keyword
                    placeholder="请输入关键词搜索"
                    :remote-method="query => searchSelectList(query, 'reconciliationCompany')"
                    :loading="searchLoadingStates['reconciliationCompany']"
                  >
                    <el-option
                      v-for="item in searchOptions['reconciliationCompany'] || []"
                      :key="item.id"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="总来佣期数" prop="totalPeriod" label-position="top">
                  <el-input
                    v-model="form.totalPeriod"
                    size="default"
                    type="number"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备注" prop="remark" label-position="top">
                  <el-input
                    v-model="form.remark"
                    size="default"
                    type="textarea"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>

        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="handleUpdate">提交</el-button>
            <el-button @click="canelEdit">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script setup name="policyInfo">
import useDictStore from '@/store/modules/dict'
import { watch, nextTick } from 'vue'

import { getAllCompanys } from '@/api/common'
import {
  getCommissionList,
  editSigalCommission,
  editMultipleCommission,
  delCommissionExpected
} 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 data = reactive({
  form: {},
  queryParams: {
    pageNo: 1,
    pageSize: 5,
    sortField: 'commissionPeriod',
    sortOrder: 'ascend',
    policyNo: props.policyNo || ''
  }
})
const { queryParams, form } = toRefs(data)
const handleEdit = row => {
  form.value = { ...row }
  editCommission.value = true
  commissionTitle.value = `修改来佣-${row.policyNo}`
}
const canelEdit = () => {
  editCommission.value = false
  form.value = {}
}
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 []
  }
}

// 添加表单子级dom
const addChildren = () => {
  // form.value = {}
  // editCommission.value = true
  // commissionTitle.value = '添加来佣'
  let obj = {
    policyNo: props.policyNo,
    commissionPeriod: '',
    commissionDate: '',
    reconciliationCompany: '',
    remark: '',
    totalPeriod: '',
    commissionName: '',
    amount: '',
    currency: ''
  }
  if (tableList.value.length == 0) {
    tableList.value.push(obj)
  } else {
    obj.reconciliationCompany = tableList.value[0].reconciliationCompany
    obj.commissionPeriod = tableList.value[0].commissionPeriod
    obj.totalPeriod = tableList.value[0].totalPeriod
    // obj.amount = tableList.value[0].amount
    obj.currency = tableList.value[0].currency
    tableList.value.push(obj)
  }

  total.value = total.value + 1
}

// 处理单个提交
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()
    }
  })
  // if (obj.commissionExpectedBizId) {
  //   editSigalCommission(obj).then(res => {
  //     if (res.code == 200) {
  //       proxy.$message.success('提交成功')
  //       editCommission.value = false
  //       form.value = {}
  //       getTableList()
  //     }
  //   })
  // }
  // else {
  //   obj.policyNo = props.policyNo
  //   editMultipleCommission({ commissionExpectedAddDtoList: [obj] }).then(res => {
  //     if (res.code == 200) {
  //       proxy.$message.success('添加成功')
  //       editCommission.value = false
  //       form.value = {}
  //       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 {
    getCommissionList(queryParams.value).then(response => {
      if (response.code == 200) {
        total.value = oldTotal.value = response.data.total

        tableList.value = response.data.records
        loading.value = false
      }
    })
  } catch (error) {
    tableList.value = []
  } finally {
    loading.value = false
  }
}
watch(
  () => props.activeName,
  newVal => {
    if (newVal === 'expectedCommission') {
      searchOptions.value['reconciliationCompany'] = dictStore.insureCompanyList
      getTableList()
    }
  }
)
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>
