<template>
  <div class="pbbasic">
    <el-container>
      <el-header>
        <div class="rect rect-form">
          <el-form
            :inline="true"
            :model="searchForm"
            size="mini"
            style="height: 47px">
            <el-form-item style="width: 200px">
              <el-input placeholder="耳标" style="width: 200px" v-model="searchForm.eartag"></el-input>
            </el-form-item>
            <el-form-item style="width: 140px">
              <el-select placeholder="性别" style="width: 140px" v-model="searchForm.sex">
                <el-option
                  v-for="item in gender"
                  :key="item.label"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item style="width: 140px">
              <el-select placeholder="品种" style="width: 140px" v-model="searchForm.breed">
                <el-option
                  v-for="item in breedList"
                  :key="item.label"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item style="width: 140px">
              <el-select placeholder="健康状况" style="width: 140px" v-model="searchForm.healthStatus">
                <el-option
                  v-for="item in healthStatus"
                  :key="item.label"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item style="width: 140px">
              <el-select placeholder="养殖状态" style="width: 140px" v-model="searchForm.outFenceStatus">
                <el-option
                  v-for="item in outFenceStatus"
                  :key="item.label"
                  :label="item.label"
                  :value="item.value">
                </el-option></el-select>
            </el-form-item>
            <el-form-item style="width: 140px">
              <el-select placeholder="猪舍" 
                style="width: 140px" 
                v-model="searchForm.pigstyId">
                <el-option
                  v-for="item in pigstyList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item style="width: 140px">
              <el-select 
                placeholder="单元" 
                style="width: 140px" 
                ref="unit"
                v-model="searchForm.unitId" 
                @focus="selectFocus('unit')">
                <el-option
                  v-for="item in unitSelectedList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
            <el-form-item style="width: 140px">
              <el-select 
                placeholder="栏期" 
                style="width: 140px" 
                ref="period"
                v-model="searchForm.periodId" 
                @focus="selectFocus('period')">
                <el-option
                  v-for="item in periodSelectedList"
                  :key="item.label"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
              <el-button @click="getDataList()" icon="el-icon-search">查 询</el-button>
            </el-form-item>
            <el-form-item>
                <el-button icon="el-icon-circle-close" @click="clearAll">清 空</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-header>
      <!-- 表格 -->
      <el-main>
        <div class="rect rect-table">
          <el-form size="mini" :inline="true">
            <el-form-item>
              <!-- <el-button 
                icon="el-icon-plus">
                新 增
              </el-button> -->
              <el-button 
                icon="el-icon-delete"
                type="danger"
                @click="deleteHandle()"
                :disabled="selectionDataList.length <= 0">
                删 除
              </el-button>
            </el-form-item>
          </el-form>
          <el-table
            id="select"
            height="530"
            :data="dataList"
            @selection-change="selectionChangeHandle"
            v-loading="dataListLoading"
            style="width: 100%"
            @expand-change="expandChange"
            ref="table"
            stripe
            border
            :header-cell-style="{background:'rgb(245,245,245)',color:'#000',height: '45px',fontSize: '13px',fontWeight: 'normal',borderBottom: '1px solid #ccc'}" 
            :cell-style="{color: '#888',fontSize: '13px'}"
            size="mini">
            <el-table-column
              type="selection"
              header-align="center"
              align="center"
              width="50">
            </el-table-column>
            <el-table-column
              prop="id"
              header-align="center"
              align="center"
              label="id">
            </el-table-column>
            <el-table-column
              prop="eartag"
              header-align="center"
              align="center"
              label="耳标">
            </el-table-column>
            <el-table-column
              prop="sex"
              header-align="center"
              align="center"
              label="性别">
            </el-table-column>
            <el-table-column
              prop="birthday"
              header-align="center"
              align="center"
              label="出生日期">
            </el-table-column>
            <el-table-column
              header-align="center"
              align="center"
              label="健康状态">
              <template slot-scope="scope">
                <span>{{scope.row.healthStatus? '健康': '不健康'}}</span>
              </template>
            </el-table-column>
            <el-table-column
              header-align="center"
              align="center"
              label="养殖状态">
              <template slot-scope="scope">
                <span>{{ outFenceStatus[scope.row.outFenceStatus].label }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="breed"
              header-align="center"
              align="center"
              label="品种">
            </el-table-column>
            <el-table-column
              prop="pigstyName"
              header-align="center"
              align="center"
              label="栋舍">
            </el-table-column>
            <el-table-column
              prop="unitName"
              header-align="center"
              align="center"
              label="单元">
            </el-table-column>
            <el-table-column
              prop="periodName"
              header-align="center"
              align="center"
              label="栏期">
            </el-table-column>
            <el-table-column
              header-align="center"
              align="center"
              label="操作">
              <template slot-scope="scope">
                <el-button
                  v-if="isAuth('sys:user:update')"
                  type="text"
                  size="medium"
                  @click="addOrUpdateHandle(scope.row)"
                  style="color: rgb(24,144,255)">
                  修改
                </el-button>
                <el-button
                  v-if="isAuth('sys:user:delete')"
                  type="text"
                  size="medium"
                  @click="deleteHandle(scope.row.id)"
                  style="color: rgb(24,144,255)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="block">
            <el-pagination
              @size-change="sizeChangeHandle"
              @current-change="currentChangeHandle"
              :current-page="pageIndex"
              :page-sizes="[10, 20, 30, 50, 100]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalPage">
            </el-pagination>
          </div>
          <el-dialog
            :title="!form.id ? '新增' : '修改'"
            :close-on-click-modal="false"
            :visible.sync="visible"
            @close="cancel"
            style="width: 50%; margin: auto">
            <el-form
              :model="form"
              :rules="dataRule"
              ref="form"
              @keyup.enter.native="formSubmit()"
              label-width="80px"
              size="mini"
              style="padding: 0 60px 0 40px">
              <el-form-item label="所属猪舍" prop="pigstyId">
                <el-select
                  v-model="form.pigstyId"
                  placeholder="请选择所属猪舍"
                  style="width: 100%">
                  <el-option
                    v-for="item in pigstyList"
                    :key="item.label"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="单元编号" prop="unitId">
                <el-select
                  v-model="form.unitId"
                  placeholder="请选择所属单元"
                  style="width: 100%">
                  <el-option
                    v-for="item in unitSelectedList"
                    :key="item.label"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <!-- <el-form-item label="栏期编号" prop="periodId">
                <el-select
                  v-model="form.periodId"
                  placeholder="请选择所属栏期"
                  @change="ifPigsty('periodId')"
                  style="width: 100%">
                  <el-option
                    v-for="item in periodSelectedList"
                    :key="item.label"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item> -->
              <el-form-item label="耳标" prop="eartag">
                <el-input
                  v-model="form.eartag"
                  placeholder="请输入耳标"
                  style="width: 100%">
                </el-input>
              </el-form-item>
              <el-form-item label="性别" prop="sex">
                <el-select
                  v-model="form.sex"
                  placeholder="请选择性别"
                  style="width: 100%">
                  <el-option
                    v-for="item in gender"
                    :key="item.label"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="出生日期" prop="birthday">
                <el-date-picker
                  v-model="form.birthday"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="请选择出生日期"
                  @change="changeBirth"
                  style="width: 100%">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="健康状况" prop="healthStatus">
                <el-select
                  v-model="form.healthStatus"
                  placeholder="请选择健康状况"
                  style="width: 100%">
                  <el-option
                    v-for="item in healthStatus"
                    :key="item.label"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="体重" prop="weight">
                <el-input-number
                  v-model="form.weight"
                  :step="0.01"
                  :max="1000000"
                  :min="0"
                  style="width: 85%">
                </el-input-number>
                千克
              </el-form-item>
              <el-form-item label="品种" prop="breed">
                <el-input
                  v-model="form.breed"
                  placeholder="请输入品种"
                  style="width: 100%">
                </el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="cancel" style="background-color: rgb(24,144,255);color: #fff;border-color: rgb(24,144,255)">关闭</el-button>
              <el-button type="primary" @click="formSubmit()" style="background-color: rgb(24,144,255);color: #fff;border-color: rgb(24,144,255)">确定</el-button>
            </span>
          </el-dialog>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>

export default {
  data() {
    return {
      searchForm: {
        eartag: '',
        sex: '',
        breed: '',
        healthStatus: '',
        outFenceStatus: '',
        // periodId: '',
        pigstyId: '',
        unitId: ''
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      selectionDataList: [],
      visible: false,
      form: {
        id: "",
        unitId: "",
        weight: "",
        whereDidYouGo: "",
        dayAge: "",
        eartag: "",
        healthStatus: "",
        breed: "",
        birthday: "",
        sex: "",
        pigstyId: "",
        // periodId: "",
        farmId: "",
      },
      // pastureList: [], // 牧场list
      pigstyList: [], // 猪舍list
      unitList: [], // 单元list
      unitSelectedList: [], // 选择过后的单元list
      periodList: [], // 栏期list
      periodSelectedList: [], // 选择过后的栏期list
      health: [
        {
          value: true,
          label: "健康",
        },
        {
          value: false,
          label: "不健康",
        },
      ],
      gender: [
        {
          value: "公",
          label: "公",
        },
        {
          value: "母",
          label: "母",
        },
      ],
      breedList: [],
      healthStatus: [
          {
            value: 1,
            label: '健康'
          },
          {
            value: 0,
            label: '不健康'
          }
        ],
        outFenceStatus: [
          {
            value: 0,
            label: '育肥'
          },
          {
            value: 1,
            label: '出栏'
          }
        ],
      row: {},
      dataRule: {
        farmId: [
          { required: true, message: "牧场不能为空", trigger: "blur" },
        ],
        pigstyId: [
          { required: true, message: "猪舍不能为空", trigger: "blur" },
        ],
        unitId: [{ required: true, message: "单元不能为空", trigger: "blur" }],
        // periodId: [
        //   { required: true, message: "栏期不能为空", trigger: "blur" },
        // ],
        eartag: [{ required: true, message: "耳标不能为空", trigger: "blur" }],
        sex: [{ required: true, message: "性别不能为空", trigger: "blur" }],
        birthday: [
          { required: true, message: "出生日期不能为空", trigger: "blur" },
        ],
        healthStatus: [],
        weight: [],
        breed: [{ required: true, message: "品种不能为空", trigger: "blur" }],
      },
      labelPosition: 'right',
      searchForm: {
        eartag: '',
        sex: '',
        breed: '',
        healthStatus: '',
        outFenceStatus: '',
        periodId: '',
        pigstyId: '',
        unitId: ''
      },
      eartags: [] // 被删除的猪只耳标
    }
  },
  activated() {
    this.getDataList();
  },
  methods: {
    // 左侧树形控件调用getDataList
    getPigs (val) {
      console.log(val);
    },
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true;
      // 获取所有猪只信息
      this.$http({
        url: this.$http.adornUrl("/management/yearpigbase/list"),
        method: "get",
        params: this.$http.adornParams({
          page: this.pageIndex,
          limit: this.pageSize,
          'eartag': this.searchForm.eartag || undefined,
          'sex': this.searchForm.sex || undefined,
          'breed': this.searchForm.breed || undefined,
          'healthStatus': this.searchForm.healthStatus || (this.searchForm.healthStatus === 0?this.searchForm.healthStatus: undefined),
          'outFenceStatus': this.searchForm.outFenceStatus || (this.searchForm.outFenceStatus === 0?this.searchForm.outFenceStatus: undefined),
          'periodId': this.searchForm.periodId || undefined,
          'pigstyId': this.searchForm.pigstyId || undefined,
          'unitId': this.searchForm.unitId || undefined
        })
      }).then(async ({ data }) => {
        // 猪舍List
        this.pigstyList = []
        let pigstyList = []
        let pigstyR = await this.$http({
          url: this.$http.adornUrl("/management/pigsty/findAll"),
          method: "get",
          params: this.$http.adornParams({})
        })
        pigstyR.data.all && (pigstyList = pigstyR.data.all)
        pigstyList.forEach(pigsty => {
          let item = {
            value: pigsty.id,
            label: pigsty.number
          }
          this.pigstyList.push(item)
        })
        console.log(this.pigstyList);
        // 单元List
        this.unitList = []
        let unitList = []
        let unitR = await this.$http({
          url: this.$http.adornUrl("/management/unit/findAll"),
          method: "get",
          params: this.$http.adornParams({})
        })
        unitR.data.all && (unitList = unitR.data.all)
        unitList.forEach(unit => {
          let item = {
            value: unit.id,
            label: unit.number,
            pigstyId: unit.pigstyId
          }
          this.unitList.push(item)
        })
        // 栏期List
        this.periodList = []
        let periodList = []
        let periodR = await this.$http({
          url: this.$http.adornUrl("/management/period/findAll"),
          method: "get",
          params: this.$http.adornParams({})
        })
        periodR.data.all && (periodList = periodR.data.all)
        periodList.forEach(period => {
          let item = {
            value: period.id,
            label: period.number,
            pigstyId: period.pigstyId
          }
          this.periodList.push(item)
        })
        this.periodSelectedList = this.searchForm.pigstyId? this.periodList.filter(item => item.pigstyId === this.searchForm.pigstyId): this.periodList
        this.unitSelectedList = this.searchForm.pigstyId? this.unitList.filter(item => item.pigstyId === this.searchForm.pigstyId): this.unitList
        // 品种list
        this.breedList = []
        let breedList = []
        let breedR = await this.$http({
          url: this.$http.adornUrl("/management/basebloodline/findAll"),
          method: "get",
          params: this.$http.adornParams({})
        })
        breedR.data.all && (breedList = breedR.data.all)
        breedList.forEach(breed => {
          let item = {
            value: breed.name,
            label: breed.name
          }
          this.breedList.push(item)
        })
        if (data && data.code === 0) {
          this.dataList = data.page.list;
          this.totalPage = data.page.totalCount;
          // console.log(data.page.list);
          // // 单元对应
          // this.dataList.forEach((item) => {
          //   for (let unit of this.unitList) {
          //     if (item.unitId === unit.id) {
          //       item.unitNumber = unit.number;
          //       item.farmId = unit.farmId;
          //       item.pigstyId = unit.pigstyId;
          //       break;
          //     }
          //   }
          // });
          // // // 牧场对应
          // // this.dataList.forEach((item) => {
          // //   for (let pasture of this.pastureList) {
          // //     if (item.farmId === pasture.id) {
          // //       item.name = pasture.name;
          // //       break;
          // //     }
          // //   }
          // // });
          // // 猪舍对应
          // this.dataList.forEach((item) => {
          //   for (let pighouse of this.pighouseList) {
          //     if (item.pigstyId === pighouse.id) {
          //       item.phNumber = pighouse.number;
          //       break;
          //     }
          //   }
          // });
          // // 栏期对应
          // this.dataList.forEach((item) => {
          //   for (let period of this.periodList) {
          //     if (item.periodId === period.id) {
          //       item.periodNumber = period.number;
          //       break;
          //     }
          //   }
          // });
          // 初始化时，选择后的与未选择的list相同
          // this.phSelectedList = this.pighouseList;
          // this.unSelectedList = this.unitList;
          // this.peSelectedList = this.periodList;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
    },
    // // 根据栋舍选择限制单元和栏期
    // pigstyChange (val) {
    //   this.unitSelectedList = this.unitList.filter(item => item.pigstyId === val)
    //   this.periodSelectedList = this.periodList.filter(item => item.pigstyId === val)
    // },
    // 点击 单元or栏期的选择框
    selectFocus (val) {
      if (!this.searchForm.pigstyId) {
        this.$message.error('请先选择猪舍')
        this.searchForm[val + 'Id'] = ''
        setTimeout(() => {
          this.$refs[val].blur()
        }, 10)
      }
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    // 展开年猪具体信息，关闭另外的具体信息
    expandChange(val) {
      if (val !== this.row) {
        this.$refs.table.toggleRowExpansion(this.row, false);
        this.row = val;
      }
      console.log(val);
    },
    // 获取出生日期
    changeBirth(val) {
      let birth = new Date(val);
      let now = new Date();
      let days = now.getTime() - birth.getTime();
      if (days < 0) {
        this.$confirm(`出生日期有误`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            console.log("还没出生呢...");
          })
          .catch(() => {});
      }
      this.form.dayAge = parseInt(days / (1000 * 60 * 60 * 24));
    },
    // 搜索表单清空
    clearAll () {
      for (let i in this.searchForm) {
        this.searchForm[i] = ''
      }
      this.unitSelectedList = this.unitList
      this.periodSelectedList = this.periodList
    },
    // 获取dayAge
    changeDay(val) {
      let now = new Date();
      let birth = new Date(now.setDate(now.getDate() - val));
      let month =
        birth.getMonth() < 9
          ? "0" + (birth.getMonth() + 1)
          : birth.getMonth() + 1;
      let date = birth.getDate() < 10 ? "0" + birth.getDate() : birth.getDate();
      this.form.birthday = `${birth.getFullYear()}-${month}-${date}`;
    },
    // // 获取到了牧场 → 猪舍 + 单元 + 栏期处理
    // getPasture(val) {
    //   /** 关于猪舍 */
    //   //  → 限制猪舍
    //   this.phSelectedList = [];
    //   this.pighouseList.forEach((item) => {
    //     if (item.farmId === val) {
    //       this.phSelectedList.push(item);
    //     }
    //   });
    //   // 判断当前 猪舍 是否需要清除
    //   let pigsty = this.pigstyByYid(this.form.pigstyId);
    //   if (pigsty && pigsty.farmId !== val) {
    //     this.form.pigstyId = "";
    //   }
    //   /** 关于单元 */
    //   //  → 限制单元
    //   this.unSelectedList = [];
    //   this.unitList.forEach((item) => {
    //     if (item.farmId === val) {
    //       this.unSelectedList.push(item);
    //     }
    //   });
    //   // 判断当前 单元 是否需要清除
    //   let unit = this.UnitByIid(this.form.unitId);
    //   if (unit && unit.farmId !== val) {
    //     this.form.unitId = "";
    //   }
    //   /** 关于栏期 */
    //   //  → 限制栏期
    //   this.peSelectedList = [];
    //   this.periodList.forEach((item) => {
    //     if (item.farmId === val) {
    //       this.peSelectedList.push(item);
    //     }
    //   });
    //   // 判断当前 栏期 是否需要清除
    //   let period = this.periodByJid(this.form.periodId);
    //   if (period && period.farmId !== val) {
    //     this.form.periodId = "";
    //   }
    // },
    // // 获取到猪舍 → 牧场 + 猪舍自身 + 单元 + 栏期处理
    // getPigsty(val) {
    //   //  → 反向确定牧场
    //   let pigsty = this.pigstyByYid(this.form.pigstyId);
    //   this.form.farmId = pigsty.farmId;
    //   // → 先获取猪舍，没有确定牧场的情况下，限制猪舍自身
    //   this.phSelectedList = this.xidYlist(pigsty.farmId);
    //   /** 关于单元 */
    //   // → 限制单元
    //   this.unSelectedList = [];
    //   this.unitList.forEach((item) => {
    //     if (item.pigstyId === val) {
    //       this.unSelectedList.push(item);
    //     }
    //   });
    //   // 判断当前 单元 是否需要清除
    //   let unit = this.UnitByIid(this.form.unitId);
    //   if (unit && unit.pigstyId !== val) {
    //     this.form.unitId = "";
    //   }
    //   /** 关于栏期 */
    //   // → 限制栏期
    //   this.peSelectedList = [];
    //   this.periodList.forEach((item) => {
    //     if (item.pigstyId === val) {
    //       this.peSelectedList.push(item);
    //     }
    //   });
    //   // 判断当前 栏期 是否需要清除
    //   let period = this.periodByJid(this.form.periodId);
    //   if (period && period.pigstyId !== val) {
    //     this.form.periodId = "";
    //   }
    // },
    // // 获取到了单元 → 牧场 + 猪舍 + 单元自身处理
    // getUnit(val) {
    //   let unit = this.UnitByIid(val);
    //   // 反向确定 牧场 + 猪舍
    //   this.form.farmId = unit.farmId;
    //   this.form.pigstyId = unit.pigstyId;
    //   // 反向确定 猪舍selectedList + 单元selectedList + 栏期selectedList
    //   this.phSelectedList = this.xidYlist(unit.farmId);
    //   this.unSelectedList = this.yidIlist(unit.pigstyId);
    //   this.peSelectedList = this.yidJlist(unit.pigstyId);
    //   // 判断当前栏期是否需要清除
    //   let period = this.periodByJid(this.form.periodId);
    //   if (period && period.pigstyId !== unit.pigstyId) {
    //     this.form.periodId = "";
    //   }
    // },
    // // 根据牧场id → 限制猪舍selectedList
    // xidYlist(farmId) {
    //   let phSelectedList = [];
    //   this.pighouseList.forEach((item) => {
    //     if (item.farmId === farmId) {
    //       phSelectedList.push(item);
    //     }
    //   });
    //   return phSelectedList;
    // },
    // // 根据猪舍id → 限制栏期selectedList
    // yidJlist(pigstyId) {
    //   let peSelectedList = [];
    //   this.periodList.forEach((item) => {
    //     if (item.pigstyId === pigstyId) {
    //       peSelectedList.push(item);
    //     }
    //   });
    //   return peSelectedList;
    // },
    // // 根据猪舍id → 限制单元selectedList
    // yidIlist(pigstyId) {
    //   let unSelectedList = [];
    //   this.unitList.forEach((item) => {
    //     if (item.pigstyId === pigstyId) {
    //       unSelectedList.push(item);
    //     }
    //   });
    //   return unSelectedList;
    // },
    // // 根据猪舍id → 返回猪舍信息
    // pigstyByYid(pigstyId) {
    //   for (let item of this.pighouseList) {
    //     if (item.id === pigstyId) {
    //       return item;
    //     }
    //   }
    //   return null;
    // },
    // // 根据栏期id → 返回栏期信息
    // periodByJid(periodId) {
    //   for (let item of this.periodList) {
    //     if (item.id === periodId) {
    //       return item;
    //     }
    //   }
    //   return null;
    // },
    // // 根据单元id → 返回单元信息
    // UnitByIid(unitId) {
    //   for (let item of this.unitList) {
    //     if (item.id === unitId) {
    //       return item;
    //     }
    //   }
    //   return null;
    // },
    // // 获取到栏期 → 牧场 + 猪舍 + 单元自身处理
    // getPeriod(val) {
    //   let period = this.periodByJid(val);
    //   // 反向确定牧场 + 猪舍
    //   this.form.farmId = period.farmId;
    //   this.form.pigstyId = period.pigstyId;
    //   // 反向确定 猪舍selectedList + 单元selectedList + 栏期selectedList
    //   this.phSelectedList = this.xidYlist(period.farmId);
    //   this.unSelectedList = this.yidIlist(period.pigstyId);
    //   this.peSelectedList = this.yidJlist(period.pigstyId);
    //   // 判断当前 单元 是否需要清除
    //   let unit = this.UnitByIid(this.form.unitId);
    //   if (unit && unit.pigstyId !== period.pigstyId) {
    //     this.form.unitId = "";
    //   }
    // },
    // 新增 or 修改单元
    addOrUpdateHandle(row) {
      // 显示牧场新增 or 修改面板
      this.visible = true;
      console.log(row);
      if (row) {
        // this.form = row;
        this.form.id = row.id
        this.form.unitId = row.unitId
        this.form.pigstyId = row.pigstyId
        this.form.dayAge = row.dayAge
        this.form.eartag = row.eartag
        this.form.healthStatus = row.healthStatus
        this.form.weight = row.weight
        this.form.whereDidYouGo = row.whereDidYouGo
        this.form.breed = row.breed
        this.form.birthday = row.birthday
        this.form.sex = row.sex
        this.unitSelectedList = this.unitList.filter(item => item.pigstyId === this.form.pigstyId)
        // this.form.periodId = row.periodId
      }
    },
    // 选择n个牧场
    selectionChangeHandle(val) {
      this.selectionDataList = [];
      val.forEach((item) => {
        this.selectionDataList.push(item.id);
      });
      this.eartags = val.map(pig => pig.eartag)
    },
    // 删除n个猪
    deleteHandle(id) {
      this.eartags = id? [this.dataList.filter(pig => pig.id === id)[0].eartag]: this.eartags
      this.$confirm(`确定删除耳标号${this.eartags.join()}的猪只？`, "提示", {
        showCancelButton: true,
        showConfirmButton: true,
        cancelButtonClass: 'cancelButton',
        confirmButtonClass: 'confirmButton',
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          // 删除操作
          if (id) {
            this.selectionDataList.push(id);
          }
          if (this.selectionDataList.length <= 0) {
            return;
          }
          this.$http({
            url: this.$http.adornUrl("/management/yearpigbase/delete"),
            method: "post",
            data: this.$http.adornData(this.selectionDataList, false),
          }).then((result) => {
            if (result.data.code === 0) {
              // this.getDataList();
              // this.resetForm();
              this.$message({
                message: "成功删除年猪",
                type: "success",
                duration: 1000,
              });
              this.getDataList()
              // pageIndex修正
              // this.totalPage -= this.selectionDataList.length;
              // let pages = Math.ceil(this.totalPage / this.pageSize);
              // this.pageIndex = this.pageIndex > pages ? pages : this.pageIndex;
              // this.pageIndex = this.pageIndex < 1 ? pages : this.pageIndex;
            } else {
              this.$message.error("删除年猪失败");
            }
            this.selectionDataList = [];
            this.eartags = []
          });
        })
        .catch(() => {});
    },
    formSubmit() {
      if (this.form.id) {
        // 修改
        // // 输入是否完整
        // if (!this.confirmComplete()) {
        //   return
        // }
        // 输入是否合法
        if (!this.confirmInput()) {
          return;
        }
        // 进行修改操作
        this.$http({
          url: this.$http.adornUrl("/management/yearpigbase/update"),
          method: "post",
          data: this.$http.adornData({
            id: this.form.id,
            unitId: this.form.unitId,
            dayAge: parseInt(this.form.dayAge),
            eartag: this.form.eartag,
            healthStatus: this.form.healthStatus,
            weight: parseFloat(this.form.weight),
            whereDidYouGo: this.form.whereDidYouGo,
            breed: this.form.breed,
            birthday: this.form.birthday,
            sex: this.form.sex,
            // periodId: this.form.periodId,
            pigstyId: this.form.pigstyId,
            farmId: parseInt(this.$cookie.get('formFarmId'))
          }),
        }).then((result) => {
          if (result.data.code === 0) {
            // this.resetForm();
            // console.log(result);
            // console.log(this.form);
            this.visible = false;
            this.$message({
              message: "成功修改年猪信息",
              type: "success",
              duration: 1000,
            })
            // this.getDataList()
          } else {
            // TODO: 年猪耳标重复
            if (result.data.code === 600) {
              // this.$message.error('牧场名称 ' + result.data.msg)
              // let msg = result.data.msg.split(' ')
              // this.$message({
              //   message: `牧场名称 <p style="color:#333; display:inline">${msg[0]}</p> 已经存在！`,
              //   type: "error",
              //   duration: 1000,
              //   dangerouslyUseHTMLString: true
              // })
              this.$message.error(result.data.msg);
              return;
            }
            this.$message.error("修改年猪信息失败");
          }
        });
      } else {
        // 新增
        console.log(this.form);
        // 输入是否完整
        // if (!this.confirmComplete(1)) {
        //   return
        // }
        // 输入是否合法
        if (!this.confirmInput()) {
          return;
        }
        // 进行新增操作
        console.log("进行新增操作");
        this.$http({
          url: this.$http.adornUrl("/management/yearpigbase/save"),
          method: "post",
          data: this.$http.adornData({
            unitId: this.form.unitId,
            dayAge: parseInt(this.form.dayAge),
            eartag: this.form.eartag,
            healthStatus: this.form.healthStatus,
            weight: parseInt(this.form.weight),
            whereDidYouGo: this.form.whereDidYouGo,
            breed: this.form.breed,
            birthday: this.form.birthday,
            sex: this.form.sex,
            // periodId: this.form.periodId,
            pigstyId: this.form.pigstyId,
            farmId: parseInt(this.$cookie.get('formFarmId'))
          }),
        }).then((result) => {
          if (result.data.code === 0) {
            // 新增pageIndex的修正
            // this.totalPage++;
            // let pages = Math.ceil(this.totalPage / this.pageSize);
            // this.pageIndex = this.pageIndex < pages ? pages : this.pageIndex;
            // this.resetForm();
            // this.visible = false;
            this.$message({
              message: "成功添加年猪",
              type: "success",
              duration: 1000,
            })
            // this.getDataList()
          } else {
            // TODO: 年猪耳标重复
            if (result.data.code === 600) {
              // this.$message.error('牧场名称 ' + result.data.msg)
              // let msg = result.data.msg.split(' ')
              // this.$message({
              //   message: `牧场名称 <p style="color:#333; display:inline">${msg[0]}</p> 已经存在！`,
              //   type: "error",
              //   duration: 1000,
              //   dangerouslyUseHTMLString: true
              // })
              this.$message.error(result.data.msg);
              return;
            }
            this.$message.error("添加年猪失败");
          }
        });
      }
      this.getDataList()
    },
    // 校验输入是否完整
    validComplete(val) {
      val &&
        (delete this.form.id,
        delete this.form.deleted,
        delete this.form.fosterStatus,
        delete this.form.gmtCreate,
        delete this.form.gmtModified,
        // delete this.form.periodNumber,
        delete this.form.phNumber,
        delete this.form.unitNumber,
        delete this.form.name);
      for (let i in this.form) {
        if (!this.form[i].toString()) {
          return false;
        }
      }
      return true;
    },
    // 如不完整，则提示
    confirmComplete(val) {
      if (this.validComplete(val)) {
        return true;
      }
      this.$confirm(`请输入完整`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log("输入不完整");
        })
        .catch(() => {});
      return false;
    },
    // 校验输入是否合法
    validInput() {
      // 出生日期是否有误
      let birth = new Date(this.form.birthday);
      let now = new Date();
      let days = now.getTime() - birth.getTime();
      if (days < 0) {
        return false;
      }
      if (this.form.weight <= 0) {
        return false;
      }
      // 只允许中文、英文、数字、-、_的输入，取反
      const reg = /[^\a-\z\A-\Z0-9\u4E00-\u9FA5\_\-]/g;
      if (reg.test(this.form.eartag)) {
        return false;
      }
      if (reg.test(this.form.breed)) {
        return false;
      }
      if (reg.test(this.form.whereDidYouGo)) {
        return false;
      }
      return true;
    },
    // 如不合法，则提示
    confirmInput() {
      if (this.validInput()) {
        return true;
      }
      this.$confirm(`请检查输入项是否合法`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log("输入不合法");
        })
        .catch(() => {});
      return false;
    },
    // // 清空form
    // resetForm() {
    //   // for (let i in this.form) {
    //   //   this.form[i] = ''
    //   // }
    //   this.form.eartag = "";
    //   this.getDataList();
    // },
    // 取消
    cancel() {
      this.visible = false;
      // this.resetForm();
    },
  },
  watch: {
    'searchForm.pigstyId': {
      handler(newValue, oldValue) {
        if (oldValue) {
          this.searchForm.unitId = ''
          this.searchForm.periodId = ''
        }
        this.unitSelectedList = this.unitList.filter(item => item.pigstyId === newValue)
        this.periodSelectedList = this.periodList.filter(item => item.pigstyId === newValue)
      }
    },
    'form.pigstyId': {
      handler(newValue, oldValue) {
        if (oldValue) {
          this.form.unitId = ''
          // this.form.periodId = ''
        }
        this.unitSelectedList = this.unitList.filter(item => item.pigstyId === newValue)
        // this.periodSelectedList = this.periodList.filter(item => item.pigstyId === newValue)
      }
    }
  }
}
</script>
<style scoped>
.rect {
  background-color: #fff;
  padding: 30px 15px;
  border-radius: 5px;
  border: 1px solid #e8e8e8;
}
.rect-form {
  padding-bottom: 10px;
}
.rect-table {
  margin-top: 20px;
}
.demo-table-expand {
  font-size: 0;
  margin-left: 40px;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 80%;
}
.el-table .height {
  background: rgba(254, 254, 254, 0.5);
}
/* .cancelButton {
  background-color: rgb(24,144,255) !important;
  border-color: rgb(24,144,255) !important;
}
.confirmButton {
  background-color: rgb(24,144,255) !important;
  border-color: rgb(24,144,255) !important;
} */
/deep/ .el-table--mini td, .el-table--mini th {
  padding: 3px 0 !important;
  height: 20px !important;
}
/deep/ .el-checkbox__input.is-checked+.el-checkbox__label {
  color: rgb(24,144,255);
  background-color: rgb(24,144,255);
  border-color: rgb(24,144,255);
}
/deep/.el-table .el-checkbox__input.is-checked .el-checkbox__inner, .el-checkbox__input.is-indeterminate .el-checkbox__inner {
  background-color: rgb(24,144,255);
  border-color: rgb(24,144,255);
}
/deep/.el-table .el-checkbox__inner:hover {
  border-color: rgb(24,144,255);
}
/deep/.el-table .el-checkbox__input.is-focus .el-checkbox__inner {
  border-color: rgb(24,144,255);
}
/deep/.el-table #select .cell .el-checkbox__input.is-checked .el-checkbox__inner, .el-checkbox__input.is-indeterminate .el-checkbox__inner {
  background-color: rgb(24,144,255);
  border-color: rgb(24,144,255);
}
/* /deep/.el-button--primary {
  background-color: rgb(24,144,255);
  border-color: rgb(24,144,255);
}
/deep/ .el-button--primary:focus, .el-button--primary:hover {
  background-color: rgb(24,144,255);
  border-color: rgb(24,144,255);
} */
/* .el-message-box__btns button:focus,.el-message-box__btns button:active {
  background-color: rgb(24,144,255) !important;
  border-color: rgb(24,144,255) !important;
} */
</style>