<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="羊只id" prop="sheepId">
        <el-input v-model="queryParams.sheepId" placeholder="请输入羊只id" clearable @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item label="品种" prop="varietyId">
        <el-select v-model="queryParams.varietyId" placeholder="请选择品种" style="min-width:150px" clearable>
          <el-option v-for="item in varietyOptions" :key="item.id" :label="item.variety" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="转入牧场" prop="transTo">
        <el-input v-model="queryParams.transTo" placeholder="请输入转入牧场" clearable @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item label="当前牧场" prop="transFrom">
        <el-input v-model="queryParams.transFrom" placeholder="请输入当前牧场" clearable @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" style="width: 150px" placeholder="请选择状态" clearable>
          <el-option v-for="dict in status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker v-model="daterangeCreateTime" value-format="YYYY-MM-DD" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />
      </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="['transition_info:transition_info:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
                   v-hasPermi="['transition_info:transition_info:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
                   v-hasPermi="['transition_info:transition_info:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
                   v-hasPermi="['transition_info:transition_info:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="transition_infoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="羊只id"  align="center" prop="sheepId" />
      <el-table-column label="品种"    align="center" prop="varietyName" />
      <el-table-column label="转入牧场" align="center" prop="transTo" />
      <el-table-column label="当前牧场" align="center" prop="transFrom" />
      <el-table-column label="转场类型" align="center" prop="transType">
        <template #default="scope">
          <dict-tag :options="trans_type" :value="scope.row.transType" />
        </template>
      </el-table-column>
      <el-table-column label="技术员" align="center" prop="technician" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="comment" />
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="180">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleApprove(scope.row)"
                     v-hasPermi="['transition_info:transition_info:approve']">审批</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['transition_info:transition_info: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="500px" append-to-body>
      <el-form ref="transition_infoRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="羊只id" prop="sheepId">
          <el-input v-model="form.sheepId" placeholder="请输入羊只id" />
        </el-form-item>

        <el-form-item label="品种" prop="varietyId">
          <el-select v-model="form.varietyId" placeholder="请选择品种" clearable>
            <el-option v-for="item in varietyOptions" :key="item.id"
                       :label="item.variety" :value="Number(item.id)" />
          </el-select>
        </el-form-item>

        <el-form-item label="转入牧场" prop="transTo">
          <el-input v-model="form.transTo" placeholder="请输入转入牧场" />
        </el-form-item>

        <el-form-item label="当前牧场" prop="transFrom">
          <el-input v-model="form.transFrom" placeholder="请输入当前牧场" />
        </el-form-item>

        <el-form-item label="转场类型" prop="transType">
          <el-select v-model="form.transType" placeholder="请选择转场类型">
            <el-option v-for="dict in trans_type" :key="dict.value"
                       :label="dict.label" :value="parseInt(dict.value)" />
          </el-select>
        </el-form-item>

        <el-form-item label="技术员" prop="technician">
          <el-input v-model="form.technician" placeholder="请输入技术员" />
        </el-form-item>

        <el-form-item label="备注" prop="comment">
          <el-input v-model="form.comment" 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>

    <!-- 审批对话框 -->
    <el-dialog :title="'审批转场记录'" v-model="approveDialog" width="500px" append-to-body>
      <el-form ref="approveFormRef" :model="approveForm" label-width="120px">
        <el-form-item label="羊只id"><el-input v-model="approveForm.sheepId" disabled /></el-form-item>
        <el-form-item label="品种"><el-input :value="approveForm.varietyName" disabled /></el-form-item>
        <el-form-item label="转入牧场"><el-input v-model="approveForm.transTo" disabled /></el-form-item>
        <el-form-item label="当前牧场"><el-input v-model="approveForm.transFrom" disabled /></el-form-item>
        <el-form-item label="转场类型">
          <el-input :value="getTransTypeLabel(approveForm.transType)" disabled />
        </el-form-item>
        <el-form-item label="技术员"><el-input v-model="approveForm.technician" disabled /></el-form-item>
        <el-form-item label="备注"><el-input v-model="approveForm.comment" disabled /></el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleApproveAgree">同意</el-button>
          <el-button type="danger" @click="handleApproveReject">驳回</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Transition_info">
import { listTransition_info, getTransition_info, delTransition_info, addTransition_info, updateTransition_info } from "@/api/produce/manage_sheep/transition_info/transition_info"
import request from '@/utils/request'

const { proxy } = getCurrentInstance()
const { status, trans_type } = proxy.useDict('status', 'trans_type')

/* -------------------- 响应式数据 -------------------- */
const transition_infoList = 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 daterangeCreateTime = ref([])

const approveDialog = ref(false)
const approveForm   = ref({})

const varietyOptions = ref([])

/* -------------------- 查询 / 表单 -------------------- */
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    sheepId: null,
    varietyId: null,
    transTo: null,
    transFrom: null,
    status: null,
    createTime: null
  },
  rules: {
    sheepId: [
      { required: true, message: "羊只id不能为空", trigger: "blur" }
    ],
    varietyId: [
      { required: true, message: "品种不能为空", trigger: "change" }
    ],
    transTo: [
      { required: true, message: "转入牧场不能为空", trigger: "blur" }
    ],
    transFrom: [
      { required: true, message: "当前牧场不能为空", trigger: "blur" }
    ],
    transType: [
      { required: true, message: "转场类型不能为空", trigger: "change" }
    ],
    technician: [
      { required: true, message: "技术员不能为空", trigger: "blur" }
    ]
  }
})
const { queryParams, form, rules } = toRefs(data)

/* -------------------- 基础方法 -------------------- */
function getList() {
  loading.value = true
  queryParams.value.params = {}
  if (daterangeCreateTime.value?.length) {
    queryParams.value.params.beginCreateTime = daterangeCreateTime.value[0]
    queryParams.value.params.endCreateTime   = daterangeCreateTime.value[1]
  }
  listTransition_info(queryParams.value).then(res => {
    transition_infoList.value = res.rows
    total.value               = res.total
    loading.value             = false
  })
}

function reset() {
  form.value = {
    id: null,
    sheepId: null,
    varietyId: null,
    transTo: null,
    transFrom: null,
    transType: null,
    technician: null,
    status: null,
    comment: null,
    createBy: null,
    createTime: null
  }
  proxy.resetForm("transition_infoRef")
}

function cancel() {
  open.value = false
  reset()
}
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}
function resetQuery() {
  daterangeCreateTime.value = []
  proxy.resetForm("queryRef")
  handleQuery()
}
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加转场"
}
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getTransition_info(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改转场"
  })
}
function submitForm() {
  proxy.$refs["transition_infoRef"].validate(valid => {
    if (!valid) return
    const api = form.value.id ? updateTransition_info : addTransition_info
    api(form.value).then(() => {
      proxy.$modal.msgSuccess(form.value.id ? "修改成功" : "新增成功")
      open.value = false
      getList()
    })
  })
}
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除转场编号为"' + _ids + '"的数据项？')
    .then(() => delTransition_info(_ids))
    .then(() => {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    })
}
function handleExport() {
  proxy.download('/produce/manage_sheep/transition_info/export',
    { ...queryParams.value },
    `transition_info_${new Date().getTime()}.xlsx`)
}

/* -------------------- 审批 -------------------- */
function handleApprove(row) {
  approveForm.value = { ...row }
  approveDialog.value = true
}
function getTransTypeLabel(val) {
  const hit = trans_type.value.find(item => Number(item.value) === val)
  return hit ? hit.label : val
}
function handleApproveAgree() {
  approveForm.value.status = 1
  updateTransition_info(approveForm.value).then(() => {
    approveDialog.value = false
    proxy.$modal.msgSuccess("审批成功，状态已更新为同意")
    getList()
  })
}
function handleApproveReject() {
  approveForm.value.status = 2
  updateTransition_info(approveForm.value).then(() => {
    approveDialog.value = false
    proxy.$modal.msgSuccess("审批成功，状态已更新为驳回")
    getList()
  })
}

/* -------------------- 下拉 -------------------- */
function getVarietyOptions() {
  request({
    url: '/base/variety/list',
    method: 'get',
    params: { pageNum: 1, pageSize: 9999 }
  }).then(res => { varietyOptions.value = res.rows || [] })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('/produce/manage_sheep/transition_info/export', {
    ...queryParams.value
  }, `transition_info_${new Date().getTime()}.xlsx`)
}
// 审批记录的对话框
const approveDialog = ref(false);
const approveForm = ref({});

// 审批按钮操作
function handleApprove(row) {
  // 打开审批对话框
  approveForm.value = { ...row };
  approveDialog.value = true;
}

// 同意审批
function handleApproveAgree() {
  approveForm.value.status = 1; // 状态设置为同意
  updateTransition_info(approveForm.value).then(() => {
    approveDialog.value = false;
    proxy.$modal.msgSuccess("审批成功，状态已更新为同意");
    getList();
  }).catch((error) => {
    proxy.$modal.msgError(`审批失败：${error}`);
  });
}

// 驳回审批
function handleApproveReject() {
  approveForm.value.status = 2; // 状态设置为驳回
  updateTransition_info(approveForm.value).then(() => {
    approveDialog.value = false;
    proxy.$modal.msgSuccess("审批成功，状态已更新为驳回");
    getList();
  }).catch((error) => {
    proxy.$modal.msgError(`审批失败：${error}`);
  });
}

getList()

</script>
