<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
      
      <el-form-item label="耳号" prop="manageTagsList">
         <el-select
            v-model="queryParams.manageTagsList"
            multiple
            filterable
            remote
            reserve-keyword
            placeholder="请输入耳号搜索"
            :remote-method="searchEarNumber"
            :loading="earNumberLoading"
            style="width: 240px"
            clearable
            @change="handleQuery"
        >
          <el-option
              v-for="item in earNumberOptions"
              :key="item"
              :label="item"
              :value="item"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="干奶日期" style="width: 308px">
        <el-date-picker
            v-model="dateRange"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="技术员" prop="technicianList">
        <el-select
            v-model="queryParams.technicianList"
            multiple
            filterable
            clearable
            placeholder="请选择技术员"
            style="width: 200px"
            @change="handleQuery"
        >
          <el-option
              v-for="item in technicalOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="封闭剂" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable style="width: 120px">
           <el-option label="是" :value="1" />
           <el-option label="否" :value="0" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @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="Plus" @click="handleAdd" v-hasPermi="['drymilk:drymilk:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['drymilk:drymilk:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['drymilk:drymilk:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['drymilk:drymilk:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="drymilkList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="干奶日期" align="center" prop="datetime" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.datetime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="耳号" align="center" prop="manageTags" min-width="120" />
      <el-table-column label="品种" align="center" prop="variety" />
      <el-table-column label="事件类型" align="center" prop="eventType" />
      <el-table-column label="乳头封闭剂" align="center" prop="status">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 1" type="success">是</el-tag>
          <el-tag v-else type="info">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="转入羊舍" align="center" prop="sheepfoldName" />
      <el-table-column label="技术员" align="center" prop="tecahnician" />
      <el-table-column label="备注" align="center" prop="comment" show-overflow-tooltip />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['drymilk:drymilk:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['drymilk:drymilk:remove']">删除</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-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="drymilkRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="耳号" prop="manageTags">
          <el-input 
            v-if="!form.id"
            v-model="form.manageTags" 
            type="textarea"
            :rows="4"
            placeholder="请输入耳号，多个耳号请用空格、逗号或回车换行分隔" 
          />
          <el-input v-else v-model="form.manageTags" placeholder="请输入耳号" disabled />
        </el-form-item>
        
        <el-form-item label="干奶日期" prop="datetime">
          <el-date-picker clearable v-model="form.datetime" type="date" value-format="YYYY-MM-DD" placeholder="请选择干奶日期"></el-date-picker>
        </el-form-item>
        
        <el-form-item label="乳头封闭剂" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="转入羊舍" prop="sheepfold">
          <el-select v-model="form.sheepfold" filterable placeholder="请输入关键字选择" style="width: 100%">
            <el-option v-for="item in sheepfoldOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="技术员" prop="tecahnician">
           <el-select v-model="form.tecahnician" filterable clearable placeholder="请选择技术员" style="width: 100%">
             <el-option 
               v-for="item in technicalOptions" 
               :key="item.value" 
               :label="item.label" 
               :value="item.value"
             ></el-option>
           </el-select>
        </el-form-item>
        
        <el-form-item label="备注" prop="comment">
          <el-input v-model="form.comment" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </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 setup name="Drymilk">
import { listDrymilk, getDrymilk, delDrymilk, addDrymilk, updateDrymilk, searchEarNumbers } from "@/api/drymilk/drymilk"
import { getUserByPost } from '@/api/common/user' // 新增引入
import { listUser } from "@/api/system/user";
import axios from 'axios';
import { getToken } from "@/utils/auth"; 

const { proxy } = getCurrentInstance()

const drymilkList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const dateRange = ref([])
const sheepfoldOptions = ref([])
const userOptions = ref([])

// 耳号搜索变量
const earNumberLoading = ref(false)
const earNumberOptions = ref([])

// 新增：技术员选项
const technicalOptions = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    manageTags: null,     
    manageTagsList: [],
    technicianList: [], // 技术员多选列表
    tecahnician: null,  // 兼容旧字段
    variety: null,
    status: null,
  },
  rules: {
    manageTags: [{ required: true, message: "耳号不能为空", trigger: "blur" }],
    datetime: [{ required: true, message: "干奶日期不能为空", trigger: "blur" }],
    status: [{ required: true, message: "请选择是否使用乳头封闭剂", trigger: "change" }]
  }
})

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

// 新增：获取技术员列表
const fetchTechnicalList = () => {
  getUserByPost({ postCode: "techs" })
      .then(res => {
        if (res.code === 200 && Array.isArray(res.data)) {
          technicalOptions.value = res.data.map(item => ({
            value: item.nickName,
            label: item.nickName
          }))
        } else {
          technicalOptions.value = []
        }
      })
      .catch(err => {
        technicalOptions.value = []
      })
}

/** 远程搜索耳号 */
function searchEarNumber(query) {
  if (query) {
    earNumberLoading.value = true;
    searchEarNumbers(query).then(res => {
      earNumberLoading.value = false;
      const list = res.data || res.msg || res;
      earNumberOptions.value = Array.isArray(list) ? list : [];
    }).catch(err => {
      earNumberLoading.value = false;
      earNumberOptions.value = [];
    });
  } else {
    earNumberOptions.value = [];
  }
}

/** 查询干奶记录列表 */
function getList() {
  loading.value = true
  const params = proxy.addDateRange(queryParams.value, dateRange.value);
  
  // 处理技术员多选：转字符串传给后端
  if (queryParams.value.technicianList && queryParams.value.technicianList.length > 0) {
      params.tecahnician = queryParams.value.technicianList.join(',');
  } else {
      params.tecahnician = null;
  }
  
  // 处理耳号多选：转字符串传给后端
  if (queryParams.value.manageTagsList && queryParams.value.manageTagsList.length > 0) {
      params.manageTags = queryParams.value.manageTagsList.join(',');
  } else {
      params.manageTags = null;
  }

  listDrymilk(params).then(response => {
    drymilkList.value = response.rows
    total.value = response.total
    loading.value = false
  }).catch(() => {
    loading.value = false;
  });
}

function getSheepfoldList() {
    const url = '/drymilk/drymilk/sheepfoldList';
    const req = proxy.$request ? proxy.$request : axios.create({ baseURL: import.meta.env.VITE_APP_BASE_API, headers: { 'Authorization': 'Bearer ' + getToken() } });
    req.get(url).then(res => { sheepfoldOptions.value = res.data || res.rows || []; });
}
function getUserList() {
  listUser({ pageNum: 1, pageSize: 1000 }).then(response => { userOptions.value = response.rows; });
}

function cancel() {
  open.value = false
  reset()
}

function reset() {
  form.value = {
    id: null,
    manageTags: null,
    datetime: new Date().toISOString().split('T')[0],
    status: 0,
    sheepfold: null,
    tecahnician: null,
    comment: null
  }
  proxy.resetForm("drymilkRef")
}

function resetQuery() {
  dateRange.value = []
  queryParams.value.manageTagsList = []
  queryParams.value.technicianList = []
  earNumberOptions.value = []
  proxy.resetForm("queryRef")
  handleQuery()
}

function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

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

function handleAdd() {
  reset()
  getSheepfoldList(); 
  getUserList();      
  open.value = true
  title.value = "添加干奶记录"
}

function handleUpdate(row) {
  reset()
  getSheepfoldList();
  getUserList();
  const _id = row.id || ids.value
  getDrymilk(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改干奶记录"
  })
}

function submitForm() {
  proxy.$refs["drymilkRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateDrymilk(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addDrymilk(form.value).then(response => {
           if(response.code === 200 || response.code === undefined) { 
               proxy.$modal.msgSuccess(response.msg || "新增成功")
           } else {
               proxy.$modal.msgWarning(response.msg)
           }
          open.value = false
          getList()
        })
      }
    }
  })
}

function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除干奶记录编号为"' + _ids + '"的数据项？').then(function() {
    return delDrymilk(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

function handleExport() {
  let params = proxy.addDateRange(queryParams.value, dateRange.value);
  if (params.manageTagsList && params.manageTagsList.length > 0) {
      params.manageTags = params.manageTagsList.join(',');
  }
  if (params.technicianList && params.technicianList.length > 0) {
      params.tecahnician = params.technicianList.join(',');
  }
  proxy.download('drymilk/drymilk/export', params, `drymilk_${new Date().getTime()}.xlsx`)
}

// 初始化
getList()
getSheepfoldList()
getUserList()
fetchTechnicalList() // 初始化加载技术员列表
</script>