<template>
  <div class="app-container">
    <div class="app-container-search main-bgcolor main-radius">
      <h1 class="">采收入库</h1>
      <br />

      <!-- 搜索工作栏 -->
      <SearchForm
        ref="searchForm"
        :searchFormParam="{ queryParams, dataSource }"
        :showSearch.sync="showSearch"
        @handleQuery="handleQuery"
        @resetQuery="resetQuery"
      ></SearchForm>
    </div>

    <div class="app-container-list main-bgcolor main-radius shopping">
      <!-- 操作工具栏 -->
      <div class="shopping-top">
        <div class="shopping-title">采收入库列表</div>
        <el-button class="shopping-add-btn" type="primary" plain @click="handleAdd"
              :loading="exportLoading"  v-hasPermi="['basic:goods-info:create']">新增</el-button>
      </div>
      <!-- 列表 -->
      <el-table v-loading="loading" :data="list">
        <el-table-column label="序号" align="center" type="index" width="80" >
          <template v-slot="{ $index }">
            <span>{{($index+1)+ (queryParams.pageNo-1)*queryParams.pageSize }}</span>
          </template>
        </el-table-column>
        <el-table-column label="所属商户" align="center" prop="belongBusinessName"></el-table-column>
        <el-table-column label="采收入库时间" align="center" prop="harverstTime" width="330" >
          <template v-slot="{ row }">
            <span>{{parseTime(row.harverstTime)}}</span>
          </template>
        </el-table-column>
        <el-table-column label="采收入库单号" align="center" prop="harverstId" width="280" >
          <template slot-scope="{ row }">
            <el-tooltip class="item" effect="dark" :content="row.harverstId" placement="top">
              <div class="table-column">
                <span class="more-width-20">{{row.harverstId}}</span>
                <el-button type="text" icon="el-icon-copy-document" @click.stop="copyContent(row.harverstId)"></el-button>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <!--
        <el-table-column label="状态" align="center" prop="blockState" width="230" >
          <template slot-scope="{row}">
            <div class="table-column">
              <el-tag
                :type="row.blockState==0?'info':row.blockState == 1?'success':'danger'">
                {{filterText(row.blockState)}}
              </el-tag>
            </div>
           </template>
        </el-table-column>
        -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template v-slot="{row}">
            <el-button size="mini" type="text" @click="handleUpdate(row)"
                       v-hasPermi="['product:harvest-info:update']">编辑</el-button>
            <el-button size="mini" type="text" @click="handleWatch(row)"
                       v-hasPermi="['product:harvest-info:update']">查看</el-button>
            <el-button size="mini" type="text" @click="handleCopy(row)"
                       v-hasPermi="['product:harvest-info:delete']">复制</el-button>
            <el-button size="mini" type="text" @click="handleDelete(row)"
                       v-hasPermi="['product:harvest-info:delete']">删除</el-button>
          </template>
        </el-table-column>
        <div slot="empty">
          <EmptyTable />
        </div>
      </el-table>
      <!-- 分页组件 -->
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                  @pagination="getList"/>
    </div>


    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="1000px"  append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-position="top" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="采收入库单号" prop="harverstId">
              <el-input v-model="form.harverstId" disabled placeholder="请输入入库单号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采收入库时间" prop="harverstTime">
              <el-date-picker style="width: 100%;" :disabled="isWatch" clearable v-model="form.harverstTime" type="datetime" value-format="timestamp" placeholder="选择入库时间" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属商户" prop="belongBusinessId">
              <el-select ref="businessName" class="w100" placeholder="请选择" :disabled="isWatch || isCopy || isDisable" v-model="form.belongBusinessId" @change="changeBusiness">
                <el-option
                v-for="(item,index) in businessNameList"
                :key="index"
                :label="item.businessName"
                :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-button v-if="!isWatch && !isCopy"
        style="float: right; margin-bottom: 10px"
        type="primary"
        @click="handleSelectGoods"
        >选择商品</el-button>
      <el-table v-loading="loading" :data="form.harvestBatchs">
        <el-table-column label="商品名称" align="center" prop="goodsName" width="150" />
        <el-table-column label="商品编码" align="center" prop="goodsId" width="150" />
        <el-table-column label="生产批次编号" align="center" prop="harvestBatchId" width="220" />
        <el-table-column v-if="isWatch" label="生产日期" align="center" prop="harvestDate" width="160" >
          <template v-slot="{row}">
            <span>{{parseTime(row.harvestDate,'{y}-{m}-{d}')}}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="!isWatch" label="生产日期" align="center" prop="harvestDate" width="160" >
          <template v-slot="{row}">
            <el-date-picker
              style="width: 100%;"
              v-model="row.harvestDate"
              value-format="timestamp"
              type="date"
              placeholder="选择日期">
            </el-date-picker>
          </template>
        </el-table-column>
        <el-table-column v-if="!isWatch" label="数量" align="center" prop="goodsNum" width="160" >
          <template v-slot="{row}">
            <el-input-number class="w100" v-model="row.goodsNum" :min="1" :precision="0" label="请输入"  controls-position="right"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column v-if="isWatch" label="数量" align="center" prop="goodsNum" width="160" >
          <template v-slot="{row}">
            <span>{{row.goodsNum}}</span>
          </template>
        </el-table-column>
        <el-table-column label="商品规格" align="center" prop="goodsSpecs" width="100" />
        <el-table-column v-if="!isWatch" label="说明" align="center" prop="remarks" min-width="160" >
          <template v-slot="{row}">
            <el-input v-model="row.remarks" placeholder="请输入"></el-input>
          </template>
        </el-table-column>
        <el-table-column v-if="isWatch" label="说明" align="center" prop="remarks" min-width="160" >
          <template v-slot="{row}">
            <span>{{row.remarks}}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="!isWatch" label="操作" align="center" fixed="right" class-name="small-padding fixed-width" width="160">
          <template v-slot="{$index,row}">
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteGoods($index,row)"
                      >删除</el-button>
          </template>
        </el-table-column>
        <div slot="empty">
          <EmptyTable />
        </div>
      </el-table>
      <div slot="footer" class="dialog-footer" v-if="!isWatch">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog class="add-dialog" :title="titleInputs" :visible.sync="openInputs" width="900px" append-to-body>
       <Transfer
       ref="transfer"
       :data="inputsOptions"
       :vModel="inputCheckedIdList"
       :renderContent="renderTransferLabel"
       :titles="['可选', '已选']"
       @change="handleSelectChange"
       :leftCurrentPage="leftCurrentPage"
       :rightCurrentPage="rightCurrentPage"
       @handlePageChange="handlePageChange"
       :leftDefaultChecked="leftDefaultChecked"
       :rightDefaultChecked="rightDefaultChecked"
       ></Transfer>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitTransferForm">确 定</el-button>
        <el-button @click="openInputs = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  createHarvestInfo,
  updateHarvestInfo,
  deleteHarvestInfo,
  getHarvestInfo,
  getHarvestInfoPage,
  exportHarvestInfoExcel,
  getHarverstActive,
  getHarverstFreeze,
  getHarverstUpChain
} from "@/api/production/harvestInfo";
import SearchForm from '@/components/Customer/SearchForm'
import EmptyTable from '@/components/EmptyTable'
import Transfer from '@/components/Customer/Transfer'
import { getByBusinessInfoId } from '@/api/basic/goodsInfo'
import { getHarverstBatchIdList , deleteHarvestBatchs } from '@/api/production/harvestBatch'
import { getHarverstIdList } from '@/api/production/harvestInfo'
import { getBusinessNameList } from '@/api/basic/businessInfo';
export default {
  name: "HarvestInfo",
  components: {
    SearchForm,
    EmptyTable,
    Transfer
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采收入库列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        harverstId: null,
        harverstTime: [],
        createTime: [],
        belongBusinessId: null,
        belongBusinessName: null,
        blockChainBlockIdentity: null,
        // blockState: null, // 逻辑删除上链状态字段
        blockChainId: null,
      },
      //表单对象
      dataSource: [
        {
          key: 'harverstTime', //出库时间
          itemType: 'datePicker',
          label: '采收入库时间',
          onEnterKeyUp: this.handleQuery,
        },
        {
          key: 'harverstId', //出库单号
          itemType: 'input',
          label: '采收出库单号',
          placeholder: '请输入',
          onEnterKeyUp: this.handleQuery,
        },
        {
          key: 'belongBusinessName', //所属商户
          itemType: 'input',
          label: '所属商户',
          placeholder: '请输入',
          onEnterKeyUp: this.handleQuery,
        },
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        harverstId: [{ required: true, message: "入库单号不能为空", trigger: "blur" }],
        harverstTime: [{ required: true, message: "入库时间不能为空", trigger: "blur" }],
        belongBusinessId: [{ required: true, message: "所属商户id不能为空", trigger: "blur" }],
        belongBusinessName: [{ required: true, message: "所属商户名称不能为空", trigger: "blur" }],
      },
      getBatchIdList: [],
      // 默认表单可编辑
      isDisable: false,
      isWatch: false,
      isCopy: false,

      /***********************  穿梭弹窗相关参数  ************************/
      titleInputs: '',
      // 是否展示穿梭窗口
      openInputs: false,
      inputsOptions: [],
      // 确认选择农资列表
      inputsList: [],
      // 已选中的农资列表【临时】，只在弹窗时作为临时存放用
      inputCheckedIdList: [],
      // 这里定义俩个参数是为了每次重新打开组件时可以重置当前页码到1
      leftCurrentPage: 1,
      rightCurrentPage: 1,
      leftDefaultChecked: [],
      rightDefaultChecked: [],

      businessNameList:[],

    };
  },
  created() {
    this.getList();
    this.initDate();
  },
  methods: {
    // 初始化数据
    async initDate(){
      let res = await getBusinessNameList();
      res.data.map(item=>{
        item.label = item.businessName;
        item.value = item.id;
      });
      this.dataSource[0].options = res.data;
      this.businessNameList = res.data;
    },
    filterText(blockState){
      switch(blockState){
        case 0:
          return '未上传'
         case 1:
          return '已上传'
         case 2:
          return '已冻结'
       default :
        break;
      }
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      getHarvestInfoPage(this.queryParams).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        harverstId: undefined,
        harverstTime: undefined,
        belongBusinessId: undefined,
        belongBusinessName: undefined,
        blockChainBlockIdentity: undefined,
        blockState: undefined,
        blockChainId: undefined,
        harvestBatchs: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm","searchForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.inputsList = [];
      this.inputCheckedIdList = [];
      this.getBatchIdList = [];
      this.open = true;
      this.title = "新增采收入库";
      this.getHarverstIdList(1);
      this.initTreesferDate();
      this.isWatch = false;
      this.isCopy = false;
      this.isDisable = false;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getHarvestInfo(id).then(response => {
        this.form = response.data;
        this.inputsList = this.form.harvestBatchs.map(item => item.goodsId);
        this.inputCheckedIdList = this.form.harvestBatchs.map(item => item.goodsId);
        this.open = true;
        this.title = "编辑采收入库";
        this.initTreesferDate();
        this.isWatch = false;
        this.isCopy = false;
        this.isDisable = true;
      });
    },
    /** 查看按钮操作 */
    handleWatch(row){
      this.reset();
      const id = row.id;
      getHarvestInfo(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "查看采收入库";
        this.isWatch = true;
        this.isCopy = false;
        this.isDisable = true;
      });
    },
    /** 复制按钮操作 */
    async handleCopy(row){
      let id = row.id;
      let res = await getHarvestInfo(id);
      res.data.harvestBatchs.map(item=>{
        item.harvestBatchId = '';
      });
      this.getBatchId(res.data.harvestBatchs.length);
      this.form = {
        ...res.data,
        id: undefined,
      };
      this.getHarverstIdList(1);
      this.open = true;
      this.title = "新增采收入库";
      this.isWatch = false;
      this.isCopy = true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }

        // 修改的提交
        if (this.form.id != null) {
          updateHarvestInfo(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        let harvestBatchs = this.form.harvestBatchs;
        if( harvestBatchs.length == 0 ){
            this.$message.error('商品列表不能为空');
            return false;
        }

        for(var x=0;x<harvestBatchs.length;x++ ){
          if(!harvestBatchs[x].harvestDate){
            this.$message.error('生产日期不能为空');
            return false;
          }
        }
        createHarvestInfo(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.getList();
          this.cancel();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除采收入库编号为"' + id + '"的数据项?').then(function() {
          return deleteHarvestInfo(id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.$modal.confirm('是否确认导出所有采收入库数据项?').then(() => {
          this.exportLoading = true;
          return exportHarvestInfoExcel(params);
        }).then(response => {
          this.$download.excel(response, '采收入库.xls');
          this.exportLoading = false;
        }).catch(() => {});
    },

    // 选择添加商品
    handleSelectGoods(){
      if( !this.form.belongBusinessId ){
        this.$message.error("请先选择所属商户");
        return;
      }
      this.getGoodsNameLists();
      this.titleInputs = '选择商品';
      this.openInputs = true;
      this.inputCheckedIdList = this.form.harvestBatchs.map(item => item.goodsId);
    },

    submitTransferForm(){
      // 窗口确定，this.inputCheckedIdList
      // 确定选用，this.inputsList
      // 确定选用为空，使用窗口确定的选项参数
      if(this.inputsList.length==0){
        this.inputsList = this.inputCheckedIdList;
        this.addCheckGoods(this.inputsList);
        console.log('初次确定选用的参数',this.inputsList);
      }else{
        //不在确定选用的参数
        let newInputs = this.inputCheckedIdList.filter((t)=>!this.inputsList.includes(t));
        if(newInputs){
          this.addCheckGoods(newInputs);
        }
      }
      this.openInputs = false;
      console.log('表单参数',this.form.harvestBatchs)
    },

    // 新增确认选中的商品
    addCheckGoods(list,start=0){
      let options = this.inputsOptions;
      for( var x=0; x<options.length ; x++  ){
        if( options[x].goodsId == list[start] ){
          // options[x] 再次判断是否在this.form.harvestBatchs中
          let isHas = false;
          this.form.harvestBatchs.some(item=>{
            if(item.goodsId == options[x].goodsId ) return isHas = true;
          });
          console.log(isHas);
          if( !isHas ){
            this.form.harvestBatchs.push({
              ...options[x],
              id:undefined
            });
            this.getBatchIdList.push(options[x].goodsId);
          }
          if(list.length-1>start){
            this.addCheckGoods(list,start+1);
          } else {
            this.inputsList = this.inputCheckedIdList;
            this.getBatchId(this.getBatchIdList.length);
          }
          return false;
        }
      }
    },

    getHarverstIdList(count){
      getHarverstIdList({count}).then((res)=>{
        this.form.harverstId = res.data[0];
      });
    },

    // 生成采收批次Id列表
    getBatchId(count){
      getHarverstBatchIdList({count}).then((res)=>{
        this.getBatchIdList = [];
        let list = res.data;
        this.handleHarvestBatchs(list,0);
      });
    },

    handleHarvestBatchs(list,start){
      for(let i = 0;i<this.form.harvestBatchs.length;i++){
        console.log(this.form.harvestBatchs[i].harvestBatchId)
        if( !this.form.harvestBatchs[i].harvestBatchId ){
          this.$set(this.form.harvestBatchs[i] , 'harvestBatchId', list[start] );
          if(list.length > start){
            this.handleHarvestBatchs(list,start+1);
          }
          return false;
        }
      }
    },

    handleDeleteGoods(index, row) {
      this.inputsList.splice(index, 1);
      this.inputCheckedIdList.splice(index, 1);
      this.form.harvestBatchs.splice(index, 1);
    },

    changeBusiness(){
      this.$nextTick(async () => {
        let label = this.$refs.businessName.selected.label;
        this.form.belongBusinessName = label;
        this.form.harvestBatchs = [];
        this.inputCheckedIdList = [];
        this.inputsList = [];
      });
    },

    handleState(row,type){
      const id = row.id;
      let text;
      switch(type){
        case 'upChain':
          text = '上传';
          break;
        case 'freeze':
          text = '冻结';
          break;
        case 'active':
          text = '激活';
          break;
      }
      this.$modal.confirm(`是否确认${text}采收入库编号为${id}的数据项?`).then(function() {
          switch(type){
            case 'upChain':
              return getHarverstUpChain(id);
            case 'freeze':
              return getHarverstFreeze(id);
            case 'active':
              return getHarverstActive(id);
          }
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess(`${text}成功`);
        }).catch(() => {});
    },

    /***********************  选择商品弹窗相关事件  ************************/
    getGoodsNameLists(){
      getByBusinessInfoId({businessInfoId: this.form.belongBusinessId}).then(response => {
        const { data } = response;
        const options = [];
        for(let i in data) {
          options.push({
            key: data[i].goodsId,
            label: data[i].goodsName,
            ...data[i]
          });
        }
        this.inputsOptions = options;
      });
    },
    // 初始化商品列表
    initTreesferDate(){
      // 每次打开之前都需要初始/重置一些参数
      this.leftCurrentPage = 1;
      this.rightCurrentPage = 1;
      this.leftDefaultChecked = [];
      this.rightDefaultChecked = [];
    },
    /**
     *
     * @param {*} value 已选中的值[数组]
     * @param {*} direction 移动方向 left，right
     * @param {*} movedKeys 移动的key数组
     */
    handleSelectChange(value, direction, movedKeys) {
      this.inputCheckedIdList = value;
    },
    renderTransferLabel(h, option) {
      return <div style="display:flex;align-item: center;">
      <span title={option.goodsId} style="display: inline-block;max-width: 110px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">{ option.goodsId }</span>
      <span style='margin: 0px 30px; color: #e6ebf5;display: inline-block;'>|</span><span>{ option.goodsName }</span>
      </div>;
    },
    /*  左侧分页参数变化时  */
    // 由于vue双向绑定的一些机制，所以需要在这边给定一个方法让子组件调用并修改传入子组件的参数
    // 这里做同步修改之后，再次打开该弹窗时上面的重置数据才会被子组件监听到。。。
    // 当然如果嫌麻烦可以直接给dialog 加个if直接销毁
    handlePageChange(value, type) {
      if(type === 'left') {
        this.leftCurrentPage = value;
      } else {
        this.rightCurrentPage = value;
      }
    },

  }
};
</script>
