<template>
  <div class="app-container">
    <el-card>
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
        <el-form-item label="时间" prop="timeRange">
          <el-date-picker
            v-model="queryParams.timeRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="待宰圈号" prop="pigpenName">
          <el-input
            v-model="queryParams.pigpenName"
            placeholder="请输入待宰圈号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @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="mini"
            @click="handleAdd"
            v-hasPermi="['app:part:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDeleteAll"
            v-hasPermi="['app:part:remove']"
          >删除</el-button>
        </el-col>
        <!--      <el-col :span="1.5">-->
        <!--        <el-button-->
        <!--          type="danger"-->
        <!--          plain-->
        <!--          icon="el-icon-bell"-->
        <!--          size="mini"-->
        <!--          @click="handleSellAll"-->
        <!--          v-hasPermi="['app:part:remove']"-->
        <!--        >生猪售尽</el-button>-->
        <!--      </el-col>-->
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </el-card>
    <br>
    <el-card>
      <el-table border stripe  v-loading="loading" ref="multipleTable" :data="disposalList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"  />
        <!--  <el-table-column label="ID"  prop="id" width="80" />  -->
        <el-table-column label="分圈时间"  prop="divideTime" />
        <el-table-column label="待宰圈号"  prop="pigpenName" />
        <el-table-column label="供应商"  prop="supplierName" />
        <el-table-column label="检疫证号"  prop="animalCertNo" />
        <el-table-column label="品种"  prop="variety" />
        <el-table-column label="数量"  prop="amount" />
        <el-table-column label="批次号"  width="190" prop="seriesNo"></el-table-column>
        <el-table-column label="静养巡查情况"  prop="restInspectionId" >
          <template slot-scope="scope">
            <span v-if="scope.row.restInspectionId" @click="openModal(scope.row.restInspectionId)" class="blue">有静养巡查记录,点击查看</span>
            <span v-else>暂无静养记录</span>
          </template>
        </el-table-column>
        <el-table-column label="消毒情况"  prop="disinfect" >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.disinfect === 0" type="success">已消毒</el-tag>
            <el-tag v-if="scope.row.disinfect === 1">未消毒</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180"  class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleView(scope.row)"
            >查看</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['app:part:edit']"
              style="margin-right: 10px"
            >修改</el-button>
            <el-popconfirm
              v-hasPermi="['app:part:remove']"
              :title="'是否确认删除所选数据项？'"
              @confirm="handleDelete(scope.row)"
            >
              <el-button
                size="mini"
                type="text"
                slot="reference"
                icon="el-icon-delete"
              >删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form"  label-position="left" :model="form" :rules="rules" :disabled="isView" label-width="80px">
        <el-form-item label="进场批次" prop="entranceBatchId">
          <el-select v-model="form.entranceBatchId" style="width: 100%">
            <el-option v-for="item in batchList" :key="item.id" :value="item.id" :label="item.desc"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分圈时间" prop="divideTime">
          <el-date-picker
            v-model="form.divideTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="待宰圈号" prop="pigpenName">
          <el-select v-model="form.pigpenName" style="width: 100%">
            <el-option v-for="item in pigpenList" :key="item.id" :value="item.pigpenName" :label="item.pigpenName"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="供应商" prop="supplierName">
          <el-input v-model="form.supplierName" disabled placeholder="选择进场批次自动填充"></el-input>
        </el-form-item>
        <el-form-item label="检疫证号" prop="animalCertNo">
          <el-input v-model="form.animalCertNo" disabled placeholder="选择进场批次自动填充"></el-input>
        </el-form-item>
        <el-form-item label="品种" prop="variety">
          <el-input v-model="form.variety" disabled placeholder="选择进场批次自动填充"></el-input>
        </el-form-item>
        <el-form-item label="数量" prop="amount">
          <el-input v-model.number="form.amount"  placeholder="请输入数量"></el-input>
        </el-form-item>
        <el-form-item label="消毒情况" prop="disinfect">
          <el-select v-model="form.disinfect">
            <el-option label="已消毒" :value="0"></el-option>
            <el-option label="未消毒" :value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="!isView">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="静养巡查情况详情" :visible.sync="showModal" width="1200px" append-to-body @close="cancel">
      <el-table border stripe  :data="patrolList">
        <el-table-column label="巡查时间"  prop="restInspectionTime" />
        <el-table-column label="待宰圈号"  prop="pigpenName" />
        <el-table-column label="巡查照片"  prop="restInspectionImg" >
          <template slot-scope="scope">
            <div class="flex-div">
              <!--            <div v-for="pic in scope.row.restInspectionImg" :key="pic">-->
              <img
                v-if="scope.row.restInspectionImg"
                :src="getFullAddr(scope.row.restInspectionImg)"
                object-fit="cover"
                class="img-row"
              />
              <!--            </div>-->
            </div>
          </template>
        </el-table-column>
        <el-table-column label="巡查内容描述"  prop="restInspectionContent" />
        <el-table-column label="处理情况"  prop="handle" />
        <el-table-column label="病死病害数量"  prop="dealAmount" />
        <el-table-column label="巡查人员"  prop="userName" />
      </el-table>
      <pagination
        v-show="patrolTotal>0"
        :total="patrolTotal"
        :page.sync="pageNumPatrol"
        :limit.sync="pageSizePatrol"
        @pagination="initTable"
      />
    </el-dialog>
<!--    <el-alert-->
<!--      title="错误提示的文案"-->
<!--      type="error"-->
<!--      :closable="false"-->
<!--      effect="dark">-->
<!--    </el-alert>-->
<!--    <br />-->
<!--    <el-form ref="formSell" :model="formSell" :rules="rules"  label-width="80px">-->
<!--      <el-form-item label="操作人" prop="userName">-->
<!--        <el-input v-model="form.userName" placeholder="请输入操作人"></el-input>-->
<!--      </el-form-item>-->
<!--    </el-form>-->
<!--    <div slot="footer" class="dialog-footer">-->
<!--      <el-button type="primary" @click="submitSellForm">确 定</el-button>-->
<!--      <el-button @click="cancel">取 消</el-button>-->
<!--    </div>-->
  </div>
</template>
<script>
import { getPartPage, getPartDetail, addPartPage, editPartPage, delPartPage } from "../../../api/app/part";
import { listEntranceBatchAll } from "../../../api/app/entranceBatch";
import { getAllPigpen } from "../../../api/app/pigpen";
import { changeDate, formatDate } from "../../../utils";
import { required, rules } from "../../../utils/formRules";
import { getPatrolById } from "../../../api/app/patrol";
import { isExternal } from "@/utils/validate";
import moment from "moment";
export default {
  name: "",
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      disposalList: [],
      // 弹出层标题
      title: "",
      isView:false,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        timeRange: null,
        pigpenName: null,
        startTime: null,
        endTime: null
      },
      pickerOptions: {
        disabledDate(time) {
          // 获取当前日期
          const today = new Date();
          today.setHours(0, 0, 0, 0); // 将时间设置为当天的 00:00:00

          // 禁用今天之后的日期
          return time.getTime() > today.getTime();
        }
      },
      // 表单参数
      form: {
        id: null,
        divideTime: formatDate(new Date()),
        pigpenId: null,
        pigpenName: null,
        entranceBatchId: '',
        restInspectionId: null,
        supplierId: null,
        supplierName: null,
        variety: null,
        disinfect: 0,
        amount: null,
        animalCertNo: null
      },
      rules: {
        divideTime: [required('分圈日期不能为空')],
        pigpenName: [required('待宰圈号不能为空')],
        supplierName: [required('供应商不能为空')],
        animalCertNo: [required('检疫证号不能为空')],
        variety: [required('品种不能为空')],
        amount: [required('数量不能为空'), rules.just],
        disinfect: [required('消毒情况不能为空')],
        userName: [required('操作人不能为空')]
      },
      formSell: {
        userName: null
      },
      // 入场批次
      batchList: [],
      // 待宰圈号
      pigpenList: [],
      showModal: false,
      user: {},
      patrolList: [],
      patrolTotal: 0,
      pageNumPatrol: 1,
      pageSizePatrol: 20,
      selectId: null
    }
  },
  watch: {
    "queryParams.timeRange": {
      handler(newVal) {
        if(newVal) {
          this.queryParams.startTime = newVal[0]
          this.queryParams.endTime = newVal[1]
        } else {
          this.queryParams.startTime = null
          this.queryParams.endTime = null
        }
      },
      deep: true
    },
    "form.entranceBatchId": {
      handler(newVal) {
        if(newVal) {
          let item = this.findById(this.batchList, newVal, 'id')
          if(item) {
            //默认分圈时间根据入场时间+15min
            this.form.divideTime = moment(new Date(item.entranceTime).getTime() + 1000 * 60 * 15).format('YYYY-MM-DD HH:mm:ss');
            this.form.supplierName = item.supplierName
            this.form.supplierId = item.supplierId
            this.form.animalCertNo = item.animalCertNo
            this.form.variety = item.variety
          }
        } else {
          this.form.divideTime = moment(new Date().getTime()).format('YYYY-MM-DD HH:mm:ss');
          this.form.supplierName = null
          this.form.supplierId = null
          this.form.animalCertNo = null
          this.form.variety = null
        }
      },
      deep: true
    },
    "form.pigpenName": {
      handler(newVal) {
        if(newVal) {
          let item = this.findById(this.pigpenList, newVal, 'pigpenName')
          if(item) {
            this.form.pigpenId = item.id
          }
        } else {
          this.form.pigpenId = null
        }
      },
      deep: true
    }
  },
  created() {
    this.getPigpen()
    this.loading = false;
    this.getList();
    this.getUser()
  },
  methods: {
    //拼接完整地址
    getFullAddr(url) {
      if (url.indexOf(this.baseUrl) === -1 && !isExternal(url)) {
        url = this.baseUrl + url;
      }
      return url;
    },
    /** getUser **/
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.formSell.userName = response.data.nickName
      });
    },
    /** 待宰圈号 **/
    getPigpen() {
      getAllPigpen({isUse:0}).then(res => {
        this.pigpenList = res.data
      })
    },
    /** 入场批次 **/
    getBatch() {
      let params = {
        entranceTime: formatDate(new Date().getTime() - 1000*60 * 60 * 24 * 2)
      }
      listEntranceBatchAll(params).then(res => {
        this.batchList = res.rows
      })
    },
    /** 根据入场批次id 返回 对应的 入场批次对象 **/
    findById(arr, id, key) {
      return arr.find(item => item[key] === id);
    },
    /** 查询检验项目列表 */
    getList() {
      getPartPage(this.queryParams).then(res => {
        this.disposalList = res.data.records;
        this.total = res.data.total;
        this.loading = false;
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        timeRange: null,
        pigpenName: null,
        startTime: null,
        endTime: null
      }
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      if(this.pigpenList.length > 0) {
        this.reset();
        this.getBatch()
        this.open = true;
        this.isView = false;
        this.title = "添加分圈登记";
      } else {
        this.$modal.msgError('当前无可用圈舍')
        return
      }
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      await this.getBatch()
      const id = row.id;
      let params = {
        id: id
      }
      await getPartDetail(params).then(res => {
        this.form = res.data;
        this.open = true;
        this.isView = false;
        this.title = "修改分圈登记";
      })
    },
    /** 查看按钮操作 */
    async handleView(row) {
      this.reset();
      const id = row.id;
      await this.getBatch()
      let params = {
        id: id
      }
      await getPartDetail(params).then(res => {
        this.form = res.data;
        this.open = true;
        this.isView = true;
        this.title = "查看分圈登记";
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.showModal = false
      this.selectId = null
      this.pageNumPatrol = 1
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        divideTime: formatDate(new Date()),
        pigpenId: null,
        pigpenName: null,
        entranceBatchId: '',
        restInspectionId: null,
        supplierId: null,
        supplierName: null,
        variety: null,
        disinfect: 0,
        amount: null,
        animalCertNo: null
      };
      this.resetForm("form");
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            // 编辑
            editPartPage(this.form).then(res => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            })
          } else {
            // 新增
            addPartPage(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id;
      let params = {
        ids: ids
      }
      delPartPage(params).then(res => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      })
    },
    /** 删除按钮操作 */
    handleDeleteAll() {
      const ids = this.ids;
      this.$modal.confirm('是否确认删除所选数据项？').then(() => {
        let params = {
          ids: ids.join(',')
        }
        delPartPage(params).then(res => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
          this.$refs.multipleTable.clearSelection();
        })
      })
    },
    openModal(item) {
      this.selectId = item
      this.showModal = true
      this.initTable()
    },
    initTable() {
      let params = {
        id: this.selectId ,
        pageNum: this.pageNumPatrol,
        pageSize: this.pageSizePatrol
      }
      getPatrolById(params).then(res => {
        this.patrolList = res.data.records;
        this.patrolTotal = res.data.total;
      })
    },
    submitSellForm() {
      this.$refs["formSell"].validate(valid => {
        if (valid) {
          addReportPage(this.formSell).then(res => {
            this.$modal.msgSuccess("操作成功");
            this.showModal = false
            this.getList();
          })
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
  .blue {
    color: #00afff;
    cursor: pointer;
  }
  .flex-div {
    display: flex;
    justify-content: center;
  }
  .img-row {
    width: 50px;
    height: 50px;
    margin: 0 10px;
  }
</style>

