<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:patrol:add']"
          >新增</el-button>
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAddBatch"
            v-hasPermi="['app:patrol: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:patrol: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" height="600" 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="restInspectionTime" />
        <el-table-column label="待宰圈号"  prop="pigpenName" />
        <el-table-column label="批次号"  width="190" prop="seriesNo" />
        <el-table-column label="巡查照片"  prop="restInspectionImg" width="200" >
          <template slot-scope="scope">
            <div class="flex-div">
              <div v-for="pic in scope.row.imgurl" :key="pic">
                <img
                  :src="getFullAddr(pic)"
                  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-column label="处理方式"  prop="dealWay" />-->
        <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:patrol:edit']"
              style="margin-right: 10px"
            >修改</el-button>
            <el-popconfirm
              v-hasPermi="['app:patrol: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="600px" append-to-body>
      <el-form ref="form" label-position="left" :model="form" :rules="rules" :disabled="isView" label-width="120px">
        <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="divideCircleId">
<!--          <el-input v-model="form.divideCircleId" disabled placeholder="选择待宰圈号自动填充"></el-input>-->
          <el-select style="width: 100%;" v-model="form.divideCircleId" disabled  placeholder="选择待宰圈号自动填充">
            <el-option v-for="item in options" :key="item.id" :value="item.id" :label="item.label"></el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="待宰圈号" prop="pigpenName">-->
<!--          <el-input v-model="form.pigpenName" disabled placeholder="选择分圈自动填充"></el-input>-->
<!--        </el-form-item>-->
        <el-form-item label="巡查时间" prop="restInspectionTime" v-if="!addBatch">
          <el-date-picker
            v-model="form.restInspectionTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-divider content-position="left" v-if="addBatch">巡查时间</el-divider>
        <div v-if="addBatch">
          <el-row :gutter="20" style="margin-bottom: 20px;" v-for="(item,i) in form.restInspectionTimeArr" :key="i">
            <el-col :span="10">
              <el-date-picker
                v-model="form.restInspectionTimeArr[i]"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                :rules="[{ required: true, message: '巡查时间不能为空', trigger: 'blur' }]"
                placeholder="选择日期时间">
              </el-date-picker>
            </el-col>
            <el-col :span="10">
              <el-button class="item-add" type="primary" v-if="i == form.restInspectionTimeArr.length - 1" @click="addItem(i)"
                ><i class="el-icon-plus"></i
              ></el-button>
              <el-button
                class="item-del"
                type="danger"
                v-if="i > 0 || form.restInspectionTimeArr.length > 1"
                @click="removeItem(i)"
                ><i class="el-icon-minus"></i
              ></el-button>
            </el-col>
          </el-row>
        </div>
        <el-form-item label="巡查内容描述" prop="restInspectionContent">
          <el-input type="textarea" :autosize="{ minRows: 2 }"   v-model="form.restInspectionContent" maxlength="50" show-word-limit placeholder="请输入巡查内容描述" />
        </el-form-item>
        <el-form-item label="处理情况" prop="handle">
          <el-input type="textarea" :autosize="{ minRows: 2 }"   v-model="form.handle" maxlength="50" show-word-limit placeholder="请输入处理情况" />
        </el-form-item>
        <el-form-item label="病死病害数量" prop="dealAmount">
          <el-input v-model.number="form.dealAmount"  placeholder="请输入病死病害数量"></el-input>
        </el-form-item>
        <el-form-item label="巡查人员" prop="userName">
          <el-input v-model="form.userName" show-word-limit maxlength="10"  placeholder="请输入巡查人员"></el-input>
        </el-form-item>
        <el-form-item label="巡查照片" prop="restInspectionImg">
          <ImageUpload v-model="form.restInspectionImg" />
        </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>
  </div>
</template>
<script>
import { getPatrolPage, getPatrolDetail, addPatrolPage, editPatrolPage, delPatrolPage, getPigpenByBatch,lastRecord } from "../../../api/app/patrol";
import { getAllPigpen } from "@/api/app/pigpen";
import { getPartList } from "../../../api/app/part";
import { isExternal } from "@/utils/validate";
import {getFindByKey, formatDate, changeDate} from "../../../utils";
import { required, rules } from "../../../utils/formRules";
import { getUserProfile } from "../../../api/system/user";
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,
        dealAmount: 0,
        divideCircleId: null,
        handle: '无需处理',
        pigpenName: null,
        restInspectionContent: '巡查结果正常',
        restInspectionImg: null,
        restInspectionTime: formatDate(new Date()),
        restInspectionTimeArr:[formatDate(new Date())],
        userName: null
      },
      rules: {
        divideCircleId: [required('进场批次不能为空')],
        restInspectionTime: [required('巡查时间不能为空')],
        pigpenName: [required('待宰圈号不能为空')],
        dealAmount: [required('病死病害数量不能为空')],
        userName: [required('巡查人员不能为空')]
      },
      // 分圈list
      partList: [],
      pigpenList: [],
      user: {},
      options: [],
      addBatch:false,
    }
  },
  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.pigpenName": {
      handler(newVal) {
        if(newVal) {
          let item = getFindByKey(this.pigpenList, newVal, 'pigpenName')
          if(item) {
            console.log(item)
            this.options = []
            this.getPigpenById(item.id)
          }
        } else {
          this.form.pigpenName = null
        }
      }
    },
    "form.dealAmount": {
      handler(newVal) {
        if(newVal) {
          if(newVal > 0) {
            this.form.handle = '需要处理'
            this.form.restInspectionContent = '巡查结果异常'
          } else {
            this.form.handle = '无需处理'
            this.form.restInspectionContent = '巡查结果正常'
          }
        } else {
          this.form.handle = '无需处理'
          this.form.restInspectionContent = '巡查结果正常'
        }
      }
    },
    // "form.divideCircleId": {
    //   handler(newVal) {
    //     if(newVal) {
    //       let item = getFindByKey(this.partList, newVal, 'id')
    //       if(item) {
    //         this.form.pigpenName = item.pigpenName
    //       }
    //     } else {
    //       this.form.pigpenName = null
    //     }
    //   },
    //   deep: true
    // }
  },
  created() {
    this.getUser()
    this.getPigpen()
    this.getList();
  },
  methods: {
    addItem(i) {
      //默认间隔四小时
      let newTime = moment(new Date(this.form.restInspectionTimeArr[i]).getTime() + 1000*60*60*4).format('YYYY-MM-DD HH:mm:ss');
      this.form.restInspectionTimeArr.push(newTime);
    },
    removeItem(i) {
      this.form.restInspectionTimeArr.splice(i, 1);
    },
    //获取最新添加记录的巡查时间作为默认时间
    setDefaultTime(){
      lastRecord().then(res=>{
        if(res.data){
          this.form.restInspectionTime = res.data.restInspectionTime;
          this.form.restInspectionTimeArr = [res.data.restInspectionTime];
        }
      })
    },
    /** getUser **/
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.form.userName = response.data.nickName
      });
    },
    /** 拿到待宰卷号 **/
    getPigpen() {
      getAllPigpen({isUse:1}).then(res => {

        this.pigpenList = res.data
      })
    },
    /** 根据待宰圈号拿到分圈 **/
    getPigpenById(pigpenId,divideCircleId=null) {
      let params = {
        id:divideCircleId,
        pigpenId: pigpenId
      }
      getPigpenByBatch(params).then(res => {
        console.log(res.data)
        if(res.data){
          this.options = [res.data];
          this.options.forEach(item => {
            item.label = item.id + '(' + item.supplierName + ',' + '检疫证号:' + item.animalCertNo +',数量:'+item.amount+'~'+changeDate(item.divideTime)+')'
          })
          this.form.divideCircleId = res.data.id
        }

      })
    },
    //拼接完整地址
    getFullAddr(url) {
      if (url.indexOf(this.baseUrl) === -1 && !isExternal(url)) {
        url = this.baseUrl + url;
      }
      return url;
    },
    //  /** 分圈登记列表 **/
    getPart() {
      let params = {
        startTime: formatDate(new Date().getTime() - 1000*60 * 60 * 24 * 2)
      }
      getPartList(params).then(res => {
        res.data.forEach(item => {
          item.label = item.supplierName + '~检疫证号：'+ item.animalCertNo
        })
        this.partList = res.data
      })
    },
    /** 查询检验项目列表 */
    getList() {
      getPatrolPage(this.queryParams).then(res => {
        res.data.records.forEach(item => {
          if(item.restInspectionImg) {
            item.imgurl = item.restInspectionImg.split(',')
          }
        })
        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.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // this.getPart()
      //默认巡查时间为上次最新巡查时间
      this.setDefaultTime();

      this.open = true;
      this.isView = false;
      this.title = "添加静养巡查";
    },
    /** 批量新增按钮操作 */
    handleAddBatch() {
      this.handleAdd()
      this.addBatch = true;
      this.title = "批量添加静养巡查";
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      // await this.getPart()
      const id = row.id;
      let params = {
        id: id
      }
      await getPatrolDetail(params).then(res => {
        this.form = res.data;
        this.getPigpenById(null,this.form.divideCircleId)
        this.open = true;
        this.isView = false;
        this.title = "修改静养巡查";
      })
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      const id = row.id;
      let params = {
        id: id
      }
      getPatrolDetail(params).then(res => {
        this.form = res.data;
        this.getPigpenById(null,this.form.divideCircleId)
        this.open = true;
        this.isView = true;
        this.title = "查看静养巡查";
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        dealAmount: 0,
        divideCircleId: null,
        handle: '无需处理',
        pigpenName: null,
        restInspectionContent: '巡查结果正常',
        restInspectionImg: null,
        restInspectionTime: formatDate(new Date()),
        restInspectionTimeArr:[formatDate(new Date())],
        userName: this.user.nickName
      };
      this.resetForm("form");
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            // 编辑
            editPatrolPage(this.form).then(res => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            })
          } else {
            // 新增
            addPatrolPage(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id;
      let params = {
        ids: ids
      }
      delPatrolPage(params).then(res => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      })
    },
    /** 删除按钮操作 */
    handleDeleteAll() {
      const ids = this.ids;
      this.$modal.confirm('是否确认删除所选数据项？').then(() => {
        let params = {
          ids: ids.join(',')
        }
        delPatrolPage(params).then(res => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
          this.$refs.multipleTable.clearSelection();
        })
      })
    }
  }
}
</script>

<style scoped lang="scss">
.flex-div {
  display: flex;
  justify-content: flex-start;
}
.img-row {
  width: 50px;
  height: 50px;
  margin: 0 10px;
}
</style>
