<template>
  <el-dialog v-model="dialog.visible" :title="dialog.title" width="70%" append-to-body>
    <el-card shadow="hover">
      <el-form ref="queryFormRef" :model="querySalesLog.prodSalesLogBo" :rules="rules" class="inline-form">
        <el-row>
          <el-form-item label="产品编号" prop="productCode">
            <el-select
              v-model="querySalesLog.prodSalesLogBo.productCode"
              placeholder="请输入产品编号"
              style="width: 200px"
              clearable
              filterable
              @change="selectProduct"
            >
              <template #header>
                <el-input v-model="likeName" placeholder="可根据产品名称或编号模糊查询" @input="filterByProductName"></el-input>
              </template>
              <el-option
                v-for="dict in filteredList"
                :key="dict.productCode"
                :label="dict.productCode + '-' + dict.productName"
                :value="dict.productCode"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="产品状态" prop="salesStatus" style="margin-left: 20px">
            <el-select v-model="querySalesLog.prodSalesLogBo.salesStatus" placeholder="产品状态" style="width: 200px" clearable>
              <el-option v-for="dict in sales_status" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="产品销售渠道" prop="salesChannel" style="margin-left: 20px">
            <el-select v-model="querySalesLog.prodSalesLogBo.salesChannel" placeholder="请选择产品销售渠道" style="width: 200px" clearable>
              <el-option v-for="dict in sales_channel" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="销售机构" prop="salesInstitution">
            <el-select v-model="querySalesLog.prodSalesLogBo.salesInstitution" placeholder="请选择销售机构" style="width: 200px" clearable>
              <el-option v-for="dict in sys_managecom" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="产品起售日期" prop="salesStartDate" style="margin-left: 20px">
            <el-date-picker
              v-model="querySalesLog.prodSalesLogBo.salesStartDate"
              clearable
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择产品起售日期"
            />
          </el-form-item>
          <el-form-item label="产品停售日期" prop="salesEndDate" style="margin-left: 20px">
            <el-date-picker
              v-model="querySalesLog.prodSalesLogBo.salesEndDate"
              clearable
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择产品停售日期"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item>
            <el-button v-hasPermi="['product:apply:loglist']" type="primary" icon="Search" @click="queryProductSalesLogInfo">搜索</el-button>
          </el-form-item>
          <el-form-item>
            <el-button v-hasPermi="['product:apply:logexport']" type="success" icon="Download" style="margin-left: 10px" @click="handleExport">
              下载</el-button
            >
          </el-form-item>
        </el-row>
      </el-form>
    </el-card>
    <el-card shadow="hover">
      <el-table :data="prodSalesLogVo" @selection-change="handleSelectionChange">
        <el-table-column label="产品编码" align="center" prop="productCode" />
        <el-table-column label="产品名称" align="center" prop="productName" />
        <el-table-column label="产品开放权限" align="center" prop="salesChannel">
          <template #default="scope">
            <dict-tag :options="sales_channel" :value="scope.row.salesChannel" />
          </template>
        </el-table-column>
        <el-table-column v-if="false" label="产品开放区域" align="center" prop="salesInstitution">
          <template #default="scope">
            <dict-tag :options="sys_managecom" :value="scope.row.salesInstitution" />
          </template>
        </el-table-column>
        <el-table-column label="产品起售日期" align="center" prop="salesStartDate">
          <template #default="scope">
            <span>{{ parseTime(scope.row.salesStartDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="产品停售日期" align="center" prop="salesEndDate">
          <template #default="scope">
            <span>{{ parseTime(scope.row.salesEndDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="产品停售原因" align="center" prop="stopSalesReason" />
        <el-table-column label="操作类型" align="center" prop="operateType">
          <template #default="scope">
            <dict-tag :options="sales_status" :value="scope.row.operateType" />
          </template>
        </el-table-column>
        <el-table-column label="操作人" align="center" prop="operator" />
        <el-table-column label="操作日期" align="center" prop="operateDate">
          <template #default="scope">
            <span>{{ parseTime(scope.row.salesEndDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="viewHistorytotal > 0"
        v-model:page="querySalesLog.pageQuery.pageNum"
        v-model:limit="querySalesLog.pageQuery.pageSize"
        :total="viewHistorytotal"
        @pagination="queryProductSalesLogInfo"
      />
    </el-card>
  </el-dialog>
</template>

<script setup name="apply-log" lang="ts">
import { codeList, getProductSalesLogInfo, qeuryAllProduct } from '@/api/product/apply';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

//字典转换
const { sales_status, sales_intitution, system, sys_managecom, sales_channel } = toRefs<any>(
  proxy?.useDict('sales_status', 'sales_intitution', 'system', 'sys_managecom', 'sales_channel')
);

const dialog = reactive({
  visible: false,
  title: '产品起停售历史轨迹查询'
});

const loading = ref(false);
const productCodes = ref<Array<string | number>>([]);
const prodSalesLogVo = ref([]);
const viewHistorytotal = ref(0);
const likeName = ref(''); // 模糊查询输入
const filteredList = ref([]); // 模糊查询结果列表
const baseproductList = ref([]); // 基础产品列表

const querySalesLog = ref({
  pageQuery: {
    pageNum: 1,
    pageSize: 10
  },
  prodSalesLogBo: {
    productCode: undefined,
    salesStatus: undefined,
    salesChannel: undefined,
    salesInstitution: undefined,
    salesStartDate: undefined,
    salesEndDate: undefined
  }
});

// 校验停售日期是否早于起售日期
const validateEndDate = (rule: any, value: string, callback: any) => {
  const startDate = querySalesLog.value.prodSalesLogBo.salesStartDate;
  const endDate = querySalesLog.value.prodSalesLogBo.salesEndDate;

  if (startDate && endDate && new Date(endDate) < new Date(startDate)) {
    callback(new Error('停售日期不能早于起售日期'));
  } else {
    callback();
  }
};

// 日期变化时触发校验
const validateDates = () => {
  proxy.$refs.queryFormRef.validateField('salesEndDate');
};

/** 查询所有产品编号*/
const fetchProductCodes = async () => {
  loading.value = true;
  try {
    const res = await qeuryAllProduct();
    baseproductList.value = res.data || [];
    filteredList.value = res.data || [];
    loading.value = false;
  } catch (err) {
    loading.value = false;
  }
};

// 添加校验规则
const rules = ref({
  salesEndDate: [{ validator: validateEndDate, trigger: 'change' }]
});

/** 对产品编号进行模糊查询*/
const searchProductCodes = async (code: string) => {
  if (code !== '') {
    loading.value = true;
    await codeList(code)
      .then((res) => {
        loading.value = false;
        productCodes.value = res.data || [];
      })
      .catch((err) => {
      });
  } else {
    productCodes.value = [];
  }
};

/** 根据条件查询产品起停售日志*/
const queryProductSalesLogInfo = async () => {
  await getProductSalesLogInfo(querySalesLog.value)
    .then((res) => {
      prodSalesLogVo.value = res.rows;
      viewHistorytotal.value = res.total;
    })
    .catch((err) => {
    });
};

const handleSelectionChange = (val) => {
  // 处理选择变化
};

const handleExport = () => {
  proxy?.download(
    'product/apply/exportProductLog',
    {
      ...querySalesLog.value.prodSalesLogBo
    },
    `product_log_${new Date().getTime()}.xlsx`
  );
};

const handleClose = (done: () => void) => {
  dialog.visible = false;
  done();
};

/** 产品名称模糊查询 */
const filterByProductName = () => {
  if (likeName.value) {
    filteredList.value = baseproductList.value.filter(
      (item) =>
        item.productName?.includes(likeName.value) ||
        item.productCode?.includes(likeName.value)
    );
  } else {
    filteredList.value = baseproductList.value;
  }
};

/** 产品选择后处理 */
const selectProduct = (newVal) => {
  querySalesLog.value.prodSalesLogBo.productCode = newVal;
};

onMounted(() => {
  queryProductSalesLogInfo();
  fetchProductCodes();
});

defineExpose({
  dialog,
  fetchProductCodes // 暴露方法
});
</script>
