<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="mb-[10px]">
        <div v-show="showSearch">
          <el-card shadow="hover">
            <el-form ref="queryFormRef" :inline="true" :model="queryParams" label-width="100px">
              <el-form-item label="联系方式" prop="contact">
                <el-input v-model="queryParams.contact" placeholder="请输入联系方式" @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="身份证号" prop="idCard">
                <el-input v-model="queryParams.idCard" placeholder="请输入身份证号" @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item>
                <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </div>

        <el-card class="mt-[10px]" shadow="never">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" @click="Add">新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button :disabled="ids.length == 0" type="primary" @click="Settlement">结算</el-button>
              </el-col>
              <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
          </template>

          <el-table v-loading="loading" :data="settlementList" @selection-change="handleSelectionChange">
            <el-table-column fixed="left" type="selection" width="55"></el-table-column>
            <el-table-column
              v-for="{ label, prop, align, minWidth, fixed } in headers"
              :key="prop"
              :align="align || 'center'"
              :fixed="fixed"
              :label="label"
              :min-width="minWidth || '170px'"
              prop="expertName"
            >
              <template #default="{ row }">
                <span v-if="prop == 'expertTypeMoneyFee'">{{ row.expertTypeMoneyFee || '0' }}元/次</span>
                <span v-else-if="prop == 'reviewCount'">{{ row.reviewCount || '0' }}次</span>
                <span v-else-if="prop == 'expertMoney'">{{ row.expertMoney || '0' }}元</span>
                <span v-else-if="prop == 'expertNoPayMoney'">{{ row.expertNoPayMoney || '0' }}元</span>
                <span v-else>{{ row[prop] || '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" class-name="small-padding fixed-width" fixed="right" label="操作" min-width="120px">
              <template #default="{ row }">
                <el-button link type="primary" @click="Edit(row)">修改</el-button>
                <el-button link type="danger" @click="Delete(row.moneyId)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="page.total > 0" v-model:limit="page.pageSize" v-model:page="page.pageNum" :total="page.total" @pagination="getList" />
        </el-card>
        <el-dialog v-model="dialogVisible" :before-close="handleClose" :title="dialogTitle" width="600px">
          <el-form ref="formRef" :model="form" :rules="rules" label-width="auto">
            <el-form-item label="项目名称" prop="productId">
              <el-select v-model="form.productId" filterable placeholder="请选择项目" @change="getExperts">
                <el-option v-for="item in projectOptions" :key="item.productId" :label="item.productName" :value="item.productId"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="项目阶段" prop="productType">
              <el-select v-model="form.productType" placeholder="请选择项目阶段" @change="getExperts">
                <el-option v-for="item in item_stage" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="结算专家" prop="expertId">
              <el-select v-model="form.expertId" :disabled="!form.productId || !form.productType" filterable placeholder="请选择结算专家">
                <el-option
                  v-for="item in expertOptions"
                  :key="item.expertId"
                  :label="`${item.workUnit} - ${item.expertName}（${item.contact}）`"
                  :value="item.expertId"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="专家类型" prop="expertType">
              <el-select v-model="form.expertType" placeholder="请选择专家类型">
                <el-option v-for="dict in positionList" :key="dict.value" :label="dict.label" :value="dict.label"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="服务日期" prop="reviewDate">
              <el-date-picker
                v-model="form.reviewDate"
                :disabled-date="disabledDate"
                placeholder="选择日期"
                style="flex: 1"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item label="是否结算" prop="status">
              <el-switch v-model="form.status" active-value="1" inactive-value="0" />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" :rows="5" placeholder="请输入备注" resize="none" type="textarea" />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="handleClose">取 消</el-button>
              <el-button type="primary" @click="Save">确 定</el-button>
            </span>
          </template>
        </el-dialog>
      </div>
    </transition>
  </div>
</template>

<script lang="ts" setup>
import { listProject } from '@/api/project/review';
import { getTableList, settlementManage, AddSettlement, UpdateSettlement, DeleteSettlement, getDetail } from '@/api/expertMoneyConfig/settlement';
import { listPosition } from '@/api/expert/person';
import { getExpertList } from '@/api/expertMoneyConfig/expertMoneyInfo';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { item_stage } = toRefs<any>(proxy?.useDict('item_stage'));
const settlementList = ref<any[]>([]);
const loading = ref(true);
const showSearch = ref(true);

const queryFormRef = ref<ElFormInstance>();

interface Header {
  label: string;
  prop: string;
  align?: 'center' | 'left' | 'right';
  minWidth?: string | number;
  fixed?: string;
}

const headers = ref<Header[]>([
  {
    label: '费用单号',
    prop: 'paySn',
    fixed: 'left'
  },
  {
    label: '专家名称',
    prop: 'expertName',
    fixed: 'left'
  },
  {
    label: '联系方式',
    prop: 'expertContact'
  },
  {
    label: '身份证号',
    prop: 'expertIdcard'
  },
  {
    label: '专家类别',
    prop: 'expertType'
  },
  {
    label: '费用标准',
    prop: 'expertTypeMoneyFee'
  },
  {
    label: '评审次数',
    prop: 'reviewCount'
  },
  {
    label: '项目名称',
    prop: 'productName'
  },
  {
    label: '服务日期',
    prop: 'reviewDate'
  },
  {
    label: '结算周期',
    prop: 'moneyCycle'
  },
  {
    label: '费用总额',
    prop: 'expertMoney'
  },
  {
    label: '待支付金额',
    prop: 'expertNoPayMoney'
  },
  {
    label: '备注',
    prop: 'remark'
  },
  {
    label: '计算日期',
    prop: 'createTime'
  }
]);

const page = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
});
const queryParams = ref<any>({
  contact: '',
  idCard: ''
});

const getList = async () => {
  loading.value = true;
  let params = {
    ...page.value,
    ...queryParams.value,
    status: 0
  };
  delete params.total;
  let res: any = await getTableList(params);
  if (res.code != 200) {
    ElNotification({
      title: '提示',
      message: res.msg,
      type: 'error'
    });
    return;
  }
  settlementList.value = res.rows;
  loading.value = false;
  page.value.total = res.total;
};

/** 搜索按钮操作 */
const handleQuery = () => {
  page.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/**
 * 结算
 */
const ids = ref([]);
/** 多选框选中数据 */
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map((item) => item.moneyId);
};
const Settlement = () => {
  ElMessageBox.confirm('是否确定结算？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const params = {
      ids: ids.value
    };
    let res = await settlementManage(params);
    if (res.code != 200) {
      ElNotification({
        title: '提示',
        message: res.msg,
        type: 'error'
      });
      return;
    }
    ElNotification({
      title: '提示',
      message: '结算成功！',
      type: 'success'
    });
    await getList();
  });
};
/**
 * 增、改、删
 */
const positionList = ref([]);
/** 职称等级列表 */
const getPositionList = async () => {
  const res = await listPosition();
  positionList.value = res.data;
};
const expertOptions = ref<any[]>([]);
const expertsLoading = ref(false);
const getExperts = async () => {
  form.expertId = '';
  expertOptions.value = [];
  if (!form.productId || !form.productType) return;
  let res = await getExpertList({
    productId: form.productId,
    reviewSn: form.productType
  });
  expertOptions.value = res.data;
};
// 项目列表
const projectOptions = ref<any[]>([]);
// 获取项目列表
const getProjectList = async () => {
  const res = await listProject({
    pageNum: 1,
    pageSize: 100000000
  });
  projectOptions.value = [...new Map(res.rows.map((item) => [item.productId, item])).values()];
};
const disabledDate = (time: any) => {
  return time.getTime() > Date.now() - 8.64e7;
};
const dialogVisible = ref(false);
const dialogType = ref('');
const dialogTitle = computed(() => {
  return dialogType.value == 'add' ? '新增' : '编辑';
});
const formRef = ref();
const form = reactive({
  'expertType': '',
  'expertId': '',
  'productType': '',
  'productId': '',
  'reviewDate': '',
  'status': '',
  remark: ''
});
const rules = {
  expertType: [{ required: true, message: '请选择专家类别', trigger: 'change' }],
  expertId: [{ required: true, message: '请输入专家名称', trigger: 'change' }],
  productType: [{ required: true, message: '请选择项目类型', trigger: 'change' }],
  productId: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
  reviewDate: [{ required: true, message: '请选择评审日期', trigger: 'change' }],
  status: [{ required: true }]
};
/*增*/
const Add = () => {
  dialogType.value = 'add';
  dialogVisible.value = true;
};
/*改*/
const Edit = async (row: any) => {
  const res: any = await getDetail(row.moneyId);
  if (res.code != 200) {
    ElNotification({
      title: '提示',
      message: res.msg,
      type: 'error'
    });
    return;
  }
  Object.assign(form, res.data);
  expertOptions.value = [
    {
      expertName: res.data.expertName,
      expertId: res.data.expertId,
      workUnit: res.data.expertUnit,
      contact: res.data.expertContact
    }
  ];
  dialogType.value = 'edit';
  dialogVisible.value = true;
};
const handleClose = () => {
  formRef.value?.resetFields();
  dialogVisible.value = false;
};
const Save = () => {
  formRef.value.validate(async (valid: any) => {
    if (!valid) return;
    ElMessageBox.confirm(`是否确定${dialogTitle.value}？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      const params = {
        ...form
      };
      const json = {
        add: AddSettlement,
        edit: UpdateSettlement
      };
      let res = await json[dialogType.value](params);
      if (res.code != 200) {
        ElNotification({
          title: '提示',
          message: res.msg,
          type: 'error'
        });
        return;
      }
      ElNotification({
        title: '提示',
        message: `${dialogTitle.value}成功！`,
        type: 'success'
      });
      handleClose();
      await getList();
    });
  });
};
/*删*/
const Delete = (id: any) => {
  ElMessageBox.confirm('是否确定删除？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    let res = await DeleteSettlement(id);
    if (res.code != 200) {
      ElNotification({
        title: '提示',
        message: res.msg,
        type: 'error'
      });
      return;
    }
    ElNotification({
      title: '提示',
      message: '删除成功！',
      type: 'success'
    });
    await getList();
  });
};
onActivated(() => {
  getPositionList();
  getProjectList();
  getList();
});
onMounted(() => {
  getPositionList();
  getProjectList();
  getList();
});
</script>
