<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="animalType">
          <el-select v-model="queryParams.animalType">
            <el-option v-for="(item, i) in animalList" :key="i" :value="item.typeValue" :label="item.typeName"></el-option>
          </el-select>
        </el-form-item>
        <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="produceName">
          <el-input
            v-model="queryParams.produceName"
            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:recall: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:recall: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 height="600"  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="recallTime" />
        <el-table-column label="畜种">
          <template slot-scope="scope">
            {{animalName(scope.row.animalType)}}
          </template>
        </el-table-column>
        <el-table-column label="产品名称"  prop="produceName" />
        <el-table-column label="肉商"  prop="purchaserName" />
        <el-table-column label="消费者"  prop="consumer" />
        <el-table-column label="召回数量"  prop="recallAmount">
          <template slot-scope="scope">
            <span>{{scope.row.recallAmount}}{{scope.row.unit}}</span>
          </template>
        </el-table-column>
        <el-table-column label="召回重量"  prop="recallAmount" >
          <template slot-scope="scope">
            <span>{{scope.row.recallWeight}}kg</span>
          </template>
        </el-table-column>
        <el-table-column label="召回原因"  prop="recallReason" />
        <el-table-column label="召回后处理"  prop="recallDeal" />
        <!--      <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:recall:edit']"
              style="margin-right: 10px"
            >修改</el-button>
            <el-popconfirm
              v-hasPermi="['app:recall: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="recallTime">
          <el-date-picker
            style="width: 100%"
            v-model="form.recallTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="畜种" prop="animalType">
          <el-select v-model="form.animalType">
            <el-option v-for="(item, i) in animalList" :key="i" :value="item.typeValue" :label="item.typeName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品名称" prop="produceName">
          <el-select v-model="form.produceName" style="width: 100%" placeholder="请选择产品">
            <el-option v-for="item in productionList" :key="item.id" :value="item.productName" :label="item.productName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="肉商" prop="purchaserId">
          <el-select v-model="form.purchaserId" style="width: 100%" :placeholder="isView ? '' : '请选择肉商'" filterable>
            <el-option v-for="item in purchaserList" :key="item.id" :value="item.id" :label="item.purchaserName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="消费者" prop="consumer">
          <el-input v-model="form.consumer" type="textarea" :autosize="{ minRows: 2 }"  show-word-limit maxlength="30" :placeholder="isView ? '' : '请输入消费者'" />
        </el-form-item>
        <el-form-item label="召回数量" prop="recallAmount">
          <el-input v-model="form.recallAmount" placeholder="请输入召回数量">
            <template #append>
              <span>{{form.unit}}</span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="召回重量(kg)" prop="recallWeight">
          <el-input v-model="form.recallWeight" :placeholder="isView ? '' : '请输入召回重量'" />
        </el-form-item>
        <el-form-item label="召回原因" prop="recallReason">
          <el-input type="textarea" :autosize="{ minRows: 2 }" v-model="form.recallReason" maxlength="50" show-word-limit :placeholder="isView ? '' : '请输入召回原因'" />
        </el-form-item>
        <el-form-item label="召回后处理" prop="recallDeal">
          <el-input type="textarea" :autosize="{ minRows: 2 }" v-model="form.recallDeal" maxlength="50" show-word-limit :placeholder="isView ? '' : '请输入召回后处理'" />
        </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 { getRecallPage, getRecallDetail, addRecallPage, editRecallPage, delRecallPage } from "../../../api/app/recall";
import {formatDate, getFindByKey, changeDate} from "../../../utils";
import { required , rules} from "../../../utils/formRules";
import {listProductCategoryAll} from "../../../api/app/productCategory";
import {getAllPurchaser} from "../../../api/app/purchaser";
import {mapState} from "vuex";

export default {
  name: "",
  data() {
    // 验证15位数字
    const validateNumber = (rule, value, callback) => {
      if (!/^([1-9]\d*(\.\d{1,2})?|0\.(\d[1-9]|[1-9]\d))$/.test(value)) {
        callback(new Error('必须是正数且最多两位小数'));
      } else {
        callback();
      }
    };
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      disposalList: [],
      // 弹出层标题
      title: "",
      isView:false,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        timeRange: null,
        produceName: null,
        startTime: null,
        endTime: null,
        animalType: null
      },
      pickerOptions: {
        disabledDate(time) {
          // 获取当前日期
          const today = new Date();
          today.setHours(0, 0, 0, 0); // 将时间设置为当天的 00:00:00

          // 禁用今天之后的日期
          return time.getTime() > today.getTime();
        }
      },
      // 表单参数
      form: {
        consumer: null,
        id: null,
        produceName: null,
        animalType: null,
        purchaserId: null,
        purchaserName: null,
        recallAmount: null,
        recallDeal: '无害化处理',
        recallReason: '产品质量问题',
        recallTime: changeDate(new Date()),
        unit: null,
        recallWeight: null
      },
      rules: {
        recallTime: [required('召回日期不能为空')],
        produceName: [required('产品名称不能为空')],
        recallAmount: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                // 如果没填，直接通过
                return callback();
              }
              validateNumber(rule, value, callback);
            },
            trigger: 'blur'
          }
        ],
        recallWeight: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                // 如果没填，直接通过
                return callback();
              }
              validateNumber(rule, value, callback);
            },
            trigger: 'blur'
          }
        ]
        // purchaserId: [required('肉商不能为空')],
        // recallAmount: [required('召回数量不能为空'), rules.decimals],
        // recallDeal: [required('召回后处理不能为空')],
      },
      // 产品名称列表
      productionList: [],
      // 肉商列表
      purchaserList: [],
      // 标记是否正在从详情回填
      isFromDetail: 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.purchaserId": {
      handler(newVal) {
        if (newVal) {
          let item = getFindByKey(this.purchaserList, newVal, 'id')
          if (item) {
            this.form.purchaserName = item.purchaserName
          }
        } else {
          this.form.purchaserName = null
        }
      },
      deep: true
    },
    "form.produceName": {
      handler(newVal) {
        this.productionList.forEach(item => {
          if(item.productName === newVal) {
            this.form.unit = item.unit
          }
        })
      },
      deep: true
    },
    "form.animalType": {
      handler(newVal, oldVal) {
        this.getProduction()
      },
      deep: true,
    }
  },
  computed: {
    ...mapState({
      animalList: state => state.user.animalList
    }),
    animalName() {
      return (value) => {
        if (value === null) return '未知'
        const animal = this.animalList.find(item =>
          String(item.typeValue) === String(value)
        )
        return animal ? animal.typeName : '未知'
      }
    }
  },
  created() {
    this.loading = false
    this.getPurchaser()
    this.getProduction()
    this.getList();
  },
  methods: {
    /** 肉商列表 **/
    getPurchaser() {
      getAllPurchaser().then(res => {
        this.purchaserList = res.data
      })
    },
    /** 产品列表 **/
    getProduction() {
      if (this.isFromDetail) return;
      if(this.form.animalType === null) return;
      let params = {
        animalType:  this.form.animalType,
        onSaleFlag:1
      }
      listProductCategoryAll(params).then(res => {
        this.productionList = res.rows
          if(res.rows && res.rows.length > 0) {
          } else {
            this.form.produceName = null
          }
      })
    },
    /** 查询检验项目列表 */
    getList() {
      getRecallPage(this.queryParams).then(res => {
        res.data.records.forEach(item => {
          item.recallTime = changeDate(item.recallTime)
        })
        this.disposalList = res.data.records;
        this.total = res.data.total;
        this.loading = false;
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        timeRange: null,
        produceName: null,
        startTime: null,
        endTime: null,
        animalType: null
      }
      // 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.open = true;
      this.isView = false;
      this.title = "添加产品召回";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      let params = {
        id: id
      }
      getRecallDetail(params).then(res => {
        this.isFromDetail = true
        this.form = res.data;
        this.open = true;
        this.isView = false;
        this.title = "修改产品召回";
        this.$nextTick(() => {
          this.isFromDetail = false
          this.getProduction()
        })
      })
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      const id = row.id;
      let params = {
        id: id
      }
      getRecallDetail(params).then(res => {
        this.isFromDetail = true
        this.form = res.data;
        this.open = true;
        this.isView = true;
        this.title = "查看产品召回";
        this.$nextTick(() => {
          this.isFromDetail = false
          this.getProduction()
        })
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        consumer: null,
        id: null,
        produceName: null,
        purchaserId: null,
        purchaserName: null,
        recallAmount: null,
        recallDeal: '无害化处理',
        recallReason: '产品质量问题',
        recallTime: changeDate(new Date()),
        unit: null,
        recallWeight: null,
        animalType: null
      };
      this.resetForm("form");
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            // 编辑
            editRecallPage(this.form).then(res => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            })
          } else {
            // 新增
            addRecallPage(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id;
      let params = {
        ids: ids
      }
      delRecallPage(params).then(res => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      })
    },
    /** 删除按钮操作 */
    handleDeleteAll() {
      const ids = this.ids;
      this.$modal.confirm('是否确认删除所选数据项？').then(() => {
        let params = {
          ids: ids.join(',')
        }
        delRecallPage(params).then(res => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
          this.$refs.multipleTable.clearSelection();
        })
      })
    }
  }
}
</script>

<style scoped lang="scss">

</style>
