<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="客户编号" prop="customerNo">
              <el-input v-model="queryParams.customerNo" placeholder="请输入客户编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" prop="protocolStatus">
              <el-select v-model="queryParams.protocolStatus" placeholder="请选择" clearable>
                <el-option label="生效" value="1" />
                <el-option label="待审核" value="0" />
                <el-option label="失效" value="2" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button type="primary" icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8" justify="space-between">
          <el-col :span="1.5">
            <span class="table-title">协议商品信息列表</span>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" icon="Download" @click="handleExport">导出</el-button>
            <el-button type="primary" icon="Plus" @click="handleAdd">协议新增</el-button>
            <!-- <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar> -->
          </el-col>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="infoList" @selection-change="handleSelectionChange">
        <el-table-column label="创建时间" align="center" prop="createTime" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="客户编号" align="center" prop="customerNo" width="100" />
        <el-table-column label="客户名称" align="center" prop="customerName" min-width="180" />
        <el-table-column label="业务员" align="center" prop="salesmanName" width="100" />
        <el-table-column label="客服" align="center" prop="serviceName" width="100" />
        <el-table-column label="截止时间" align="center" prop="endTime" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="商品数量" align="center" prop="productNum" width="100" />
        <!-- <el-table-column label="状态" align="center" prop="approvalStatus" width="80">
          <template #default="scope">
            <span>{{ getStatusLabel(scope.row.protocolStatus) }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" align="center" fixed="right" width="300" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" @click="handleDetail(scope.row)" >基本信息</el-button>
            <el-button v-if="isAudit === 0" link type="primary" @click="handleProductManage(scope.row)" >商品管理</el-button>
            <el-button v-if="isAudit === 1" link type="primary" @click="handleGoReview(scope.row)" >去审核</el-button>
            <!-- <el-button link type="primary" @click="handleInvalid(scope.row)" v-if="scope.row.protocolStatus === 1" >失效</el-button>
            <el-button link type="primary" @click="handleAudit(scope.row)" v-if="scope.row.protocolStatus === 0" >审核</el-button> -->
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改协议信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body>
      <el-form ref="infoFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="客户名称" prop="customerId">
          <el-select
            v-model="form.customerId"
            placeholder="请选择"
            clearable
            filterable
            :disabled="dialog.isView"
            @change="handleCustomerChange"
            style="width: 100%"
          >
            <el-option
              v-for="item in customerList"
              :key="item.id"
              :label="item.customerName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属公司" prop="companyId">
          <el-input v-model="form.customerName" disabled />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="业务员" prop="salesmanId">
              <el-input v-model="form.salesmanName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客服" prop="serviceId">
              <el-input v-model="form.serviceName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="起始时间" prop="startTime">
              <el-date-picker
                v-model="form.startTime"
                type="date"
                placeholder="请选择"
                value-format="YYYY-MM-DD"
                :disabled="dialog.isView"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="截止时间" prop="endTime">
              <el-date-picker
                v-model="form.endTime"
                type="date"
                placeholder="请选择"
                value-format="YYYY-MM-DD"
                :disabled="dialog.isView"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="附件" prop="protocolFile">
          <file-upload v-model="form.protocolFile" :disabled="dialog.isView"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="4" placeholder="请输入内容" :disabled="dialog.isView" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="!dialog.isView" :loading="buttonLoading" type="primary" @click="submitForm">确认</el-button>
          <el-button @click="cancel">{{ dialog.isView ? '关闭' : '取消' }}</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog title="审核" v-model="auditDialog.visible" width="500px" append-to-body>
      <el-form ref="auditFormRef" :model="auditForm" :rules="auditRules" label-width="80px">
        <el-form-item label="审核:" prop="protocolStatus">
          <el-select v-model="auditForm.protocolStatus" placeholder="请选择" style="width: 100%">
            <el-option label="生效" :value="1" />
            <el-option label="失效" :value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="auditButtonLoading" type="primary" @click="submitAudit">确认</el-button>
          <el-button @click="cancelAudit">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Info" lang="ts">
import { listInfo, getInfo, delInfo, addInfo, updateInfo } from '@/api/product/protocolInfo';
import { InfoVO, InfoQuery, InfoForm } from '@/api/product/protocolInfo/types';
import { listCustomerInfo } from '@/api/customer/customerInfo';
import { CustomerInfoVO } from '@/api/customer/customerInfo/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const router = useRouter();
const route = useRoute();

// 从路由获取isAudit参数
const isAudit = ref(Number(route.query.isAudit) || 0);

const infoList = ref<InfoVO[]>([]);
const customerList = ref<CustomerInfoVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const infoFormRef = ref<ElFormInstance>();
const auditFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption & { isView?: boolean }>({
  visible: false,
  title: '',
  isView: false
});

// 审核对话框
const auditDialog = reactive({
  visible: false
});

// 审核按钮loading
const auditButtonLoading = ref(false);

// 审核表单
const auditForm = ref<any>({
  id: undefined,
  protocolStatus: undefined
});

// 审核表单验证规则
const auditRules = ref({
  protocolStatus: [{ required: true, message: '请选择审核结果', trigger: 'change' }]
});

const initFormData: InfoForm = {
  id: undefined,
  protocolNo: undefined,
  customerNo: undefined,
  customerId: undefined,
  customerName: undefined,
  reviewTime: undefined,
  approvalStatus: undefined,
  startTime: undefined,
  endTime: undefined,
  productNum: undefined,
  remark: undefined,
  protocolStatus: undefined,
  salesmanId: undefined,
  salesmanName: undefined,
  companyId: undefined,
  companyName: undefined,
  serviceId: undefined,
  serviceName: undefined,
  dataSource: undefined,
  protocolFile: undefined,
  fileName: undefined,
  status: undefined,
}
const data = reactive<PageData<InfoForm, InfoQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    protocolNo: undefined,
    customerNo: undefined,
    customerId: undefined,
    customerName: undefined,
    reviewTime: undefined,
    approvalStatus: undefined,
    startTime: undefined,
    endTime: undefined,
    productNum: undefined,
    protocolStatus: undefined,
    salesmanId: undefined,
    companyId: undefined,
    serviceId: undefined,
    dataSource: undefined,
    protocolFile: undefined,
    fileName: undefined,
    status: undefined,
    platformCode: undefined,
    params: {
    }
  },
  rules: {
    customerId: [
      { required: true, message: "客户名称不能为空", trigger: "change" }
    ],
    startTime: [
      { required: true, message: "起始时间不能为空", trigger: "change" }
    ],
    endTime: [
      { required: true, message: "截止时间不能为空", trigger: "change" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询协议信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listInfo(queryParams.value);
  infoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 加载客户列表 */
const loadCustomerList = async () => {
  const res = await listCustomerInfo({ pageNum: 1, pageSize: 1000 });
  customerList.value = res.rows;
}

/** 客户选择改变 */
const handleCustomerChange = (customerId: string | number) => {
  const customer = customerList.value.find(item => item.id === customerId);
  if (customer) {
    form.value.customerNo = customer.customerNo;
    form.value.customerName = customer.customerName;
    // 公司名称显示客户名称
    form.value.companyId = customer.belongCompanyId;
    form.value.companyName = customer.customerName;

    // 从客户信息中获取业务员和客服信息
    if (customer.customerSalesInfoVo) {
      form.value.salesmanId = customer.customerSalesInfoVo.salesPersonId;
      form.value.salesmanName = customer.customerSalesInfoVo.salesPerson || '';
      form.value.serviceId = customer.customerSalesInfoVo.serviceStaffId;
      form.value.serviceName = customer.customerSalesInfoVo.serviceStaff || '';
    } else {
      form.value.salesmanId = undefined;
      form.value.salesmanName = '';
      form.value.serviceId = undefined;
      form.value.serviceName = '';
    }
  }
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  infoFormRef.value?.resetFields();
}

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: InfoVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加协议信息";
  dialog.isView = false;
}

/** 修改按钮操作 */
const handleUpdate = async (row?: InfoVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getInfo(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改协议信息";
  dialog.isView = false;
}

/** 提交按钮 */
const submitForm = () => {
  infoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateInfo(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addInfo(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: InfoVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除协议信息编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delInfo(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('product/info/export', {
    ...queryParams.value
  }, `info_${new Date().getTime()}.xlsx`)
}

/** 获取状态标签 */
const getStatusLabel = (status: number) => {
  const statusMap: Record<number, string> = {
    0: '待审核',
    1: '生效',
    2: '失效'
  };
  console.log('status', statusMap[status] || status);
  return statusMap[status] || status;
}

/** 查看基本信息 */
const handleDetail = async (row: InfoVO) => {
  reset();
  const res = await getInfo(row.id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "查看基本信息";
  dialog.isView = true;
}

/** 商品管理 */
const handleProductManage = (row: InfoVO) => {
  router.push({
    path: '/product/protocolInfo/productManage',
    query: { protocolId: row.id }
  });
}
/** 去审核 */
const handleGoReview = (row: InfoVO) => {
  router.push({
    path: '/product/protocolInfo/review',
    query: { protocolId: row.id }
  });
}

/** 失效操作 */
const handleInvalid = async (row: InfoVO) => {
  await proxy?.$modal.confirm('是否确认将该协议设为失效？');
  // TODO: 调用失效接口
  console.log('失效操作', row);
  await getList();
}

/** 审核操作 */
const handleAudit = (row: InfoVO) => {
  auditForm.value = {
    id: row.id,
    protocolStatus: undefined
  };
  auditDialog.visible = true;
}

/** 取消审核 */
const cancelAudit = () => {
  auditForm.value = {
    id: undefined,
    protocolStatus: undefined
  };
  auditFormRef.value?.resetFields();
  auditDialog.visible = false;
}

/** 提交审核 */
const submitAudit = () => {
  auditFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      auditButtonLoading.value = true;
      try {
        // 构造更新数据
        const updateData: InfoForm = {
          id: auditForm.value.id,
          protocolStatus: auditForm.value.protocolStatus
        };
        await updateInfo(updateData).finally(() => auditButtonLoading.value = false);
        proxy?.$modal.msgSuccess("审核成功");
        auditDialog.visible = false;
        await getList();
      } catch (error) {
        auditButtonLoading.value = false;
      }
    }
  });
}

onMounted(() => {
  getList();
  loadCustomerList();
});
</script>
