<template>
  <div class="app-container">
    <el-breadcrumb separator="/" class="breadcrumb">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>销售管理</el-breadcrumb-item>
      <el-breadcrumb-item>销售记录</el-breadcrumb-item>
    </el-breadcrumb>

    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="销售日期">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          size="small"
        />
      </el-form-item>

      <el-form-item label="客户名称" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户名称"
          clearable
          size="small"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="销售人员" prop="salesPersonName">
        <el-input
          v-model="queryParams.salesPersonName"
          placeholder="请输入销售人员姓名"
          clearable
          size="small"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="small"
          @click="handleAdd"
          v-hasPermi="['saleRecord:saleRecord:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="small"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['saleRecord:saleRecord:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="small"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['saleRecord:saleRecord:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="small"
          @click="handleExport"
          v-hasPermi="['saleRecord:saleRecord:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="saleRecordList" 
      @selection-change="handleSelectionChange" 
      @sort-change="handleSortChange"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" align="center" />
      
      <el-table-column label="耳号" align="center" prop="bsManageTags" width="120" show-overflow-tooltip />
      <el-table-column label="品种" align="center" prop="variety" width="100" show-overflow-tooltip />
      
      <el-table-column 
        label="羊舍" 
        align="center" 
        prop="sheepfoldId" 
        width="120" 
        :formatter="sheepfoldFormat" 
        show-overflow-tooltip 
      />

      <el-table-column label="事件类型" align="center" prop="eventType" width="100" show-overflow-tooltip />
      <el-table-column label="销售日期" align="center" prop="saleDate" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.saleDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="羊只类别" align="center" prop="sheepName" width="100" show-overflow-tooltip />
      <el-table-column label="性别" align="center" prop="gender" width="80" />
      
      <el-table-column label="月龄" align="center" prop="monthAge" width="80" sortable="custom" />
      <el-table-column label="胎次" align="center" prop="parity" width="80" sortable="custom" />
      <el-table-column label="计价方式" align="center" prop="pricingMethod" width="100" show-overflow-tooltip />
      
      <el-table-column label="单价" align="center" prop="unitPrice" width="100" sortable="custom">
        <template #default="scope">
          <span v-if="scope.row.unitPrice !== null">{{ scope.row.unitPrice }}元</span>
        </template>
      </el-table-column>
      <el-table-column label="总价" align="center" prop="totalPrice" width="100" sortable="custom">
        <template #default="scope">
          <span v-if="scope.row.totalPrice !== null">{{ scope.row.totalPrice }}元</span>
        </template>
      </el-table-column>
      <el-table-column label="总体重" align="center" prop="totalWeight" width="100" sortable="custom">
        <template #default="scope">
          <span v-if="scope.row.totalWeight">{{ scope.row.totalWeight }}kg</span>
        </template>
      </el-table-column>
      <el-table-column label="平均体重" align="center" prop="avgWeight" width="100" sortable="custom">
        <template #default="scope">
          <span v-if="scope.row.avgWeight">{{ scope.row.avgWeight }}kg</span>
        </template>
      </el-table-column>
      <el-table-column label="平均单只价格" align="center" prop="avgPricePerSheep" width="120" sortable="custom">
        <template #default="scope">
          <span v-if="scope.row.avgPricePerSheep">{{ scope.row.avgPricePerSheep }}元</span>
        </template>
      </el-table-column>
      
      <el-table-column label="销售类别" align="center" prop="saleType" width="120" :formatter="saleTypeFormat" show-overflow-tooltip />
      <el-table-column label="客户名称" align="center" prop="customerName" width="140" show-overflow-tooltip />
      <el-table-column label="客户电话" align="center" prop="customerPhone" width="130" show-overflow-tooltip />
      <el-table-column label="客户地址" align="center" prop="customerAddress" width="180" show-overflow-tooltip />
      <el-table-column label="销售人员" align="center" prop="salesPersonName" width="120" show-overflow-tooltip />
      <el-table-column label="检疫证号" align="center" prop="quarantineNo" width="130" show-overflow-tooltip />
      <el-table-column label="审批编号" align="center" prop="approvalNo" width="130" show-overflow-tooltip />
      <el-table-column label="疾病类型" align="center" prop="diseaseType" width="120" :formatter="diseaseTypeFormat" show-overflow-tooltip />
      <el-table-column label="次要原因" align="center" prop="secondaryReason" width="120" show-overflow-tooltip />
      <el-table-column label="班组" align="center" prop="groupCode" width="100" :formatter="groupFormat" />
      <el-table-column label="繁育状态" align="center" prop="breed" width="100" show-overflow-tooltip />
      
      <el-table-column label="产后天数" align="center" prop="postLambingDay" width="90" sortable="custom" />
      <el-table-column label="泌乳天数" align="center" prop="lactationDay" width="90" sortable="custom" />
      <el-table-column label="怀孕天数" align="center" prop="lambingDay" width="90" sortable="custom" />
      
      <el-table-column label="创建人" align="center" prop="createdByName" width="120" show-overflow-tooltip />
      <el-table-column label="创建日期" align="center" prop="createdAt" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="技术员" align="center" prop="technicianName" width="120" show-overflow-tooltip />
      <el-table-column label="处理人" align="center" prop="handlerName" width="120" show-overflow-tooltip />
      <el-table-column label="备注" align="center" prop="remark" width="150" show-overflow-tooltip />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150" fixed="right">
        <template #default="scope">
          <el-button
            size="small"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['saleRecord:saleRecord:edit']"
          >修改</el-button>
          <el-button
            size="small"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['saleRecord:saleRecord:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page="queryParams.pageNum"
      :limit="queryParams.pageSize"
      :page-sizes="[20, 50, 100, 200, 500, 1000, 2000]"
      @pagination="getList"
    />

    <el-dialog :title="title" v-model="open" width="1200px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="羊舍" prop="sheepfoldId">
              <el-select
                v-model="form.sheepfoldId"
                placeholder="请选择羊舍"
                clearable
                @change="handleSheepfoldChange"
                style="width: 100%"
              >
                <el-option
                  v-for="item in sheepfoldOptions"
                  :key="item.id || item.sheepfoldId"
                  :label="item.sheepfoldName || item.name"
                  :value="item.id || item.sheepfoldId"
                />
              </el-select>
            </el-form-item>
          </el-col>
           <el-col :span="12">
            <el-form-item label="耳号" prop="bsManageTagsList">
              <el-select
                v-model="form.bsManageTagsList"
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请先选择羊舍，或手动输入耳号并回车确认"
                style="width: 100%"
              >
                <el-option
                  v-for="tag in earTagOptions"
                  :key="tag"
                  :label="tag"
                  :value="tag"
                />
              </el-select>
            </el-form-item>
          </el-col>
          </el-row>
        <el-row :gutter="20">
            </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSaleRecord,
  getSaleRecord,
  delSaleRecord,
  addSaleRecord,
  updateSaleRecord,
  getSheepInfo,
} from '@/api/sale/saleRecord/saleRecord'
import { listSheepfold_management } from '@/api/fileManagement/sheepfold_management'
import { listUser } from '@/api/system/user'
import { getDicts } from '@/api/system/dict/data'
import { listCustomer } from '@/api/sale/customer/customer'

export default {
  name: 'SxSheepSale',
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      saleRecordList: [],
      title: '',
      open: false,
      dateRange: [],
      queryParams: {
        pageNum: 1,
        pageSize: 20, 
        customerName: null,    
        salesPersonName: null, 
        orderByColumn: null,   
        isAsc: null            
      },
      form: {},
      saleTypeOptions: [],
      diseaseTypeOptions: [],
      groupOptions: [],
      sheepfoldOptions: [],
      earTagOptions: [],
      userOptions: [],
      customerOptions: [],
      customerLoading: false,
      _prevTags: [],
      rules: {
        // ... rules 保持不变 ...
        sheepfoldId: [{ required: true, message: '羊舍不能为空', trigger: 'change' }],
        bsManageTagsList: [{ type: 'array', required: true, message: '至少需要一个耳号', trigger: 'change' }],
        saleDate: [{ required: true, message: '销售日期不能为空', trigger: 'change' }],
        pricingMethod: [{ required: true, message: '计价方式不能为空', trigger: 'change' }],
        unitPrice: [{ required: true, message: '单价不能为空', trigger: 'blur' }],
        saleType: [{ required: true, message: '销售类别不能为空', trigger: 'change' }],
        customerId: [{ required: true, message: '客户不能为空', trigger: 'change' }],
        salesPersonId: [{ required: true, message: '销售人员不能为空', trigger: 'change' }],
        // ...
      },
    }
  },
  computed: {
    isEliminationSale() {
      const opt = this.saleTypeOptions.find(o => o.dictValue === this.form.saleType)
      const label = opt ? opt.dictLabel : ''
      return label === '淘汰销售' || label === '淘汰屠宰'
    },
    diseaseTypeLabel() {
      const opt = this.diseaseTypeOptions.find(o => o.dictValue === this.form.diseaseType)
      return opt ? opt.dictLabel : ''
    },
  },
  watch: {
    'form.bsManageTagsList'(val = []) {
      const added = Array.isArray(val) ? val.filter(v => !this._prevTags.includes(v)) : []
      if (added.length > 0) {
        this.fetchSheepInfo(added[added.length - 1])
      }
      this._prevTags = Array.isArray(val) ? [...val] : []

      if (this.form.pricingMethod === '按个体') {
        this.calculateIndividualPrice()
      } else if (this.form.pricingMethod === '按体重') {
        this.calculateWeightPrice()
      }
    },
    'form.unitPrice': function () {
      if (this.form.pricingMethod === '按个体') {
        this.calculateIndividualPrice()
      } else if (this.form.pricingMethod === '按体重') {
        this.calculateWeightPrice()
      }
    },
    'form.totalWeight': function () {
      if (this.form.pricingMethod === '按体重') this.calculateWeightPrice()
    }
  },
  created() {
    this.getList()
    this.getDictsData()
    this.getSheepfoldOptions()
    this.getUserOptions()
    this.remoteMethodGetCustomer('')
  },
  methods: {
    disabledDate(time) {
      return time.getTime() > Date.now()
    },
    
    getList() {
      this.loading = true
      const params = { ...this.queryParams }
      if (this.dateRange && this.dateRange.length === 2) {
        params.params = {
          beginSaleDate: this.dateRange[0],
          endSaleDate: this.dateRange[1]
        }
      }

      listSaleRecord(params)
        .then(res => {
          this.saleRecordList = res.rows || []
          this.total = res.total || 0
        })
        .finally(() => (this.loading = false))
    },

    handleSortChange({ column, prop, order }) {
      this.queryParams.orderByColumn = prop 
      this.queryParams.isAsc = order === 'ascending' ? 'asc' : 'desc'
      this.getList()
    },

    // 【核心修改】前端格式化方法：将 sheepfoldId 转换为 名称
    sheepfoldFormat(row) {
      if (!row.sheepfoldId) return '';
      // 在 sheepfoldOptions 中查找
      // 兼容可能的数据结构：id/name 或 sheepfoldId/sheepfoldName
      const found = this.sheepfoldOptions.find(item => 
        (item.id == row.sheepfoldId) || (item.sheepfoldId == row.sheepfoldId)
      );
      if (found) {
        return found.sheepfoldName || found.name;
      }
      return row.sheepfoldId; // 如果没找到，显示 ID
    },

    saleTypeFormat(row) {
      return this.selectDictLabel(this.saleTypeOptions, row.saleType)
    },
    diseaseTypeFormat(row) {
      return this.selectDictLabel(this.diseaseTypeOptions, row.diseaseType)
    },
    groupFormat(row) {
      return this.selectDictLabel(this.groupOptions, row.groupCode)
    },

    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.queryParams.orderByColumn = null
      this.queryParams.isAsc = null
      if (this.$refs.table) {
        this.$refs.table.clearSort()
      }
      this.handleQuery()
    },

    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加羊只销售记录'
      this.form.eventType = '销售'
      this.form.saleDate = new Date().toISOString().slice(0, 10)
    },

    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getSaleRecord(id).then(response => {
        this.form = response.data || {}
        if (this.form.bsManageTags) {
          this.form.bsManageTagsList = String(this.form.bsManageTags).split(',').filter(Boolean)
        }
        this._prevTags = Array.isArray(this.form.bsManageTagsList) ? [...this.form.bsManageTagsList] : []
        this.open = true
        this.title = '修改羊只销售记录'
      })
    },

    cancel() {
      this.open = false
      this.reset()
    },

    reset() {
      this.form = {
        id: null,
        bsManageTags: null,
        bsManageTagsList: [],
        sheepfoldId: null,
        variety: null,
        sheepName: null,
        gender: null,
        monthAge: null,
        parity: null,
        breed: null,
        postLambingDay: null,
        lactationDay: null,
        lambingDay: null,
        eventType: '销售',
        saleDate: null,
        pricingMethod: null,
        unitPrice: null,
        totalPrice: null,
        totalWeight: null,
        avgWeight: null,
        avgPricePerSheep: null,
        saleType: null,
        diseaseType: null,
        secondaryReason: null,
        groupCode: null,
        customerId: null,
        customerName: null,
        customerPhone: null,
        customerAddress: null,
        salesPersonId: null,
        salesPersonName: null,
        quarantineNo: null,
        approvalNo: null,
        technicianId: null,
        technicianName: null,
        handlerId: null,
        handlerName: null,
        createdBy: null,
        createdByName: null,
        createdAt: null,
        remark: null
      }
      this._prevTags = []
      this.resetForm('formRef')
    },

    submitForm() {
      this.$refs.formRef.validate(valid => {
        if (!valid) return
        if (Array.isArray(this.form.bsManageTagsList) && this.form.bsManageTagsList.length > 0) {
          this.form.bsManageTags = this.form.bsManageTagsList.join(',')
        } else {
          this.form.bsManageTags = null
        }
        const api = this.form.id ? updateSaleRecord : addSaleRecord
        api(this.form)
          .then(() => {
            this.$modal.msgSuccess(this.form.id ? '修改成功' : '新增成功')
            this.open = false
            this.getList()
          })
          .catch(err => {
            console.error(err)
          })
      })
    },

    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除羊只销售记录编号为"' + ids + '"的数据项？')
        .then(() => delSaleRecord(ids))
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },

    handleExport() {
      this.$modal.confirm('是否确认导出所有羊只销售记录数据项？').then(() => {
        const params = { ...this.queryParams }
        if (this.dateRange && this.dateRange.length === 2) {
            params.params = {
            beginSaleDate: this.dateRange[0],
            endSaleDate: this.dateRange[1]
            }
        }
        this.download('/saleRecord/saleRecord/export', params, `saleRecord_${new Date().getTime()}.xlsx`)
      })
    },

    getDictsData() {
      getDicts('sale_type').then(r => (this.saleTypeOptions = r.data || []))
      getDicts('disease_type').then(r => (this.diseaseTypeOptions = r.data || []))
      getDicts('group').then(r => (this.groupOptions = r.data || []))
    },

    getSheepfoldOptions() {
      listSheepfold_management().then(r => {
        this.sheepfoldOptions = r.rows || r.data || []
      })
    },

    getUserOptions() {
      listUser().then(r => {
        this.userOptions = r.rows || r.data || []
      })
    },

    remoteMethodGetCustomer(query) {
      this.customerLoading = true
      const p = query ? { name: query } : {}
      listCustomer(p)
        .then(r => {
          this.customerOptions = r.rows || r.data || []
        })
        .finally(() => (this.customerLoading = false))
    },

    handleCustomerChange(customerId) {
      const customer = this.customerOptions.find(item => item.id === customerId)
      if (customer) {
        this.form.customerName = customer.name
        this.form.customerPhone = customer.phone
        this.form.customerAddress = customer.address
      }
    },

    handleSheepfoldChange(sheepfoldId) {
      this.form.bsManageTagsList = []
      this.earTagOptions = []
      if (sheepfoldId) {
        // 模拟数据或根据羊舍加载真实耳号
        this.earTagOptions = ['1001', '1002', '1003', '1004', '1005']
      }
    },

    fetchSheepInfo(bsManageTags) {
      if (!bsManageTags) return
      getSheepInfo(bsManageTags).then(response => {
        if (response.code === 200 && response.data) {
          const data = response.data
          this.form.variety = data.variety
          this.form.sheepName = data.sheepName
          this.form.gender = data.gender
          this.form.monthAge = data.monthAge
          this.form.parity = data.parity
          this.form.breed = data.breed
          this.form.postLambingDay = data.postLambingDay
          this.form.lactationDay = data.lactationDay
          this.form.lambingDay = data.lambingDay
          if (!this.form.sheepfoldId && data.sheepfoldId) {
            this.form.sheepfoldId = data.sheepfoldId
            this.handleSheepfoldChange(data.sheepfoldId)
          }
        } else {
          this.$modal.msgError(response.msg || '未查询到羊只信息')
        }
      })
    },

    handlePricingMethodChange(method) {
      if (method === '按个体') {
        this.form.totalWeight = null
        this.form.avgWeight = null
        this.calculateIndividualPrice()
      } else if (method === '按体重') {
        this.calculateWeightPrice()
      }
    },

    calculateIndividualPrice() {
      if (this.form.pricingMethod !== '按个体') return
      const unitPrice = parseFloat(this.form.unitPrice) || 0
      const count = Array.isArray(this.form.bsManageTagsList) ? this.form.bsManageTagsList.length : 0
      const total = unitPrice * count
      this.form.totalPrice = Number.isFinite(total) ? Number(total.toFixed(2)) : 0
      this.form.avgPricePerSheep = Number.isFinite(unitPrice) ? Number(unitPrice.toFixed(2)) : 0
    },

    calculateWeightPrice() {
      if (this.form.pricingMethod !== '按体重') return
      const unitPrice = parseFloat(this.form.unitPrice) || 0
      const totalWeight = parseFloat(this.form.totalWeight) || 0
      const count = Array.isArray(this.form.bsManageTagsList) && this.form.bsManageTagsList.length > 0 ? this.form.bsManageTagsList.length : 1
      const total = unitPrice * totalWeight
      this.form.totalPrice = Number.isFinite(total) ? Number(total.toFixed(2)) : 0
      const avgW = totalWeight / count
      this.form.avgWeight = Number.isFinite(avgW) ? Number(avgW.toFixed(2)) : 0
      const avgP = this.form.totalPrice / count
      this.form.avgPricePerSheep = Number.isFinite(avgP) ? Number(avgP.toFixed(2)) : 0
    },

    handleSaleTypeChange() {
      if (!this.isEliminationSale) {
        this.form.diseaseType = null
        this.form.groupCode = null
        this.form.secondaryReason = null
      }
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate(['diseaseType', 'groupCode', 'secondaryReason'])
      })
    },

    handleDiseaseTypeChange() {
      if (this.diseaseTypeLabel !== '病残羊') {
        this.form.secondaryReason = null
      }
      this.$nextTick(() => this.$refs.formRef.clearValidate('secondaryReason'))
    },
  },
}
</script>

<style scoped>
.breadcrumb { margin-bottom: 16px; }
.app-container { position: relative; }
.el-table { width: 100%; overflow-x: auto; }
</style>