<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="115px">
      <el-form-item label="采购申请单号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="要求收货仓库" prop="warehouseName">
        <el-input
          v-model="queryParams.warehouseName"
          placeholder="请输入"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="要求到货时间" prop="expectedTime">
        <el-date-picker clearable size="small" style="width: 215px"
          v-model="queryParams.expectedTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择要求到货时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker clearable size="small" style="width: 215px"
          v-model="queryParams.createTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="商品编码" prop="spuCode">
        <el-input
          v-model="queryParams.spuCode"
          placeholder="请输入"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="SKU编码" prop="skuCode">
        <el-input
          v-model="queryParams.skuCode"
          placeholder="请输入"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item style="margin-left: 47px;">
        <el-button type="cyan" 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"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['oms:apply:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['oms:apply:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['oms:apply:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['oms:apply:export']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table height="500" border v-loading="loading" :data="applyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号"  width="55" type="index" align="center" />
      <el-table-column label="id" prop="id" v-if="false"></el-table-column>
      <el-table-column label="采购申请单号" align="center" prop="code" />
      <el-table-column label="要求收货仓库" align="center" prop="warehouseName" />
      <el-table-column label="要求到货时间" align="center" prop="expectedTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expectedTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="status" >
          <template slot-scope="scope">
              <el-tag prop="status" v-for="(item, index) in statusOptions"    v-if="scope.row.status==item.dictValue">{{item.dictLabel}}</el-tag>
          </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核时间" align="center" prop="auditTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.auditTime)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请数量" align="center" prop="planNum" >
      </el-table-column>
      <el-table-column label="已下采购数量" align="center" prop="alreadyNum" />
      <el-table-column label="未下采购数量" align="center" prop="waitNum" />
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdateStatus(scope.row)"
          >审核</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['oms:apply:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDetails(scope.row)"
            v-hasPermi="['store:storeOrder:query']"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改采购申请单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1030px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <!-- <el-form-item label="未下采购" prop="waitNum" v-if="false">
            <el-input v-model="form.waitNum" />
        </el-form-item> -->
        <el-form-item label="收货仓库id" prop="warehouseId" v-if="false">
            <el-input v-model="form.warehouseId" placeholder="请输入"  />
        </el-form-item>
        <el-row>
          <el-col :span="8">
            <el-form-item label="采购申请单号" prop="code">
              <el-input v-model="form.code"  placeholder="自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="要求收货仓库" prop="warehouseName" >
              <el-select v-model="form.warehouseName"  @change="selectWarehouse">
                <el-option v-for="item in warehouseOptions" 
                    :label="item.warehouseName"
                    :value="item.warehouseName"/>            
              </el-select>
            </el-form-item>
            
          </el-col>  
          <el-col :span="8">
            <el-form-item label="要求到货时间" prop="expectedTime">
              <el-date-picker clearable size="small" style="width: 200px"
                v-model="form.expectedTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择要求到货时间">
              </el-date-picker>
            </el-form-item>
          </el-col>        
        </el-row>        
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button type="primary" plain @click="showDialog">添加商品</el-button>
        </el-form-item>
      </el-form>
      <el-form-item label="申请数量" prop="planNum" v-if="false">
          <el-input v-model="form.planNum" />
      </el-form-item>
      <el-table border :data="selectProducts" v-model="form.products">
        <el-table-column label="序号"  width="55" type="index" align="center" /> 
        <el-table-column label="商品图片" align="center" width="160">
        <template slot-scope="scope">
          <el-popover
            placement="right"
            title=""
            trigger="hover"
          >
            <img slot="reference" :src="scope.row.image" width="100">
            <img :src="scope.row.image" style="max-width: 150px;">
            </el-popover>
          </template>
        </el-table-column>       
        <el-table-column label="供应商名称"  align="center" prop="supplierName" />
        <el-table-column label="商品编码"  align="center" prop="spuCode" />
        <el-table-column label="商品名称"  align="center" prop="spuName" />
        <el-table-column label="SKU编码"  align="center" prop="skuCode" />
        <el-table-column label="SKU名称" align="center" prop="skuName" />
        <el-table-column label="申请数量" align="center">
          <template slot-scope="scope">
            <el-input v-model.number="scope.row.planNum" type="number"></el-input>
          </template>          
        </el-table-column>
        <el-table-column label="已下采购" align="center">
          <template slot-scope="scope">
            <el-input v-model.number="scope.row.alreadyNum" type="number"></el-input>
          </template>          
        </el-table-column>
        <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="danger" icon="el-icon-delete" @click="removeSelected(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogVisible"  title="选择商品" width="1200px" @selection-change="handleSelectionChange">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="供应商名称" prop="supplierName">
        <el-input
          v-model="queryParams.supplierName"
          placeholder="请输入"
          clearable
          size="small"
          @keyup.enter.native="handleQuerys"
        />
      </el-form-item>
      <el-form-item label="供应商编码" prop="supplierCode">
        <el-input
          v-model="queryParams.supplierCode"
          placeholder="请输入"
          clearable
          size="small"
          @keyup.enter.native="handleQuerys"
        />
      </el-form-item>
      <el-form-item label="商品名称" prop="spuName">
        <el-input
          v-model="queryParams.spuName"
          placeholder="请输入商品名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuerys"
        />
      </el-form-item>
       <el-form-item label="商品编号" prop="spuCode">
        <el-input
          v-model="queryParams.spuCode"
          placeholder="请输入商品编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuerys"
        />
      </el-form-item>
      <el-form-item label="SKU编号" prop="skuCode">
        <el-input
          v-model="queryParams.skuCode"
          placeholder="请输入SKU编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuerys"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuerys">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuerys">重置</el-button>
      </el-form-item>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getproductList"></right-toolbar>
    </el-form>
      <el-table border ref="dataList" v-loading="loading" :data="productOptions">
        <el-table-column label="序号"  width="55" type="index" align="center" />
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="供应商编码"  align="center" prop="supplierCode" />
        <el-table-column label="商品图片" align="center" width="160" v-if="false">
        <template slot-scope="scope">
          <el-popover
            placement="right"
            title=""
            trigger="hover"
          >
            <img slot="reference" :src="scope.row.image" width="100">
            <img :src="scope.row.image" style="max-width: 150px;">
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="供应商名称"  align="center" prop="supplierName" />
        <el-table-column label="商品编码"  align="center" prop="spuCode" />
        <el-table-column label="商品名称"  align="center" prop="spuName" />
        <el-table-column label="SKU编码"  align="center" prop="skuCode" />
        <el-table-column label="SKU名称" align="center" prop="skuName" />
        <el-table-column label="供应商商品编码"  align="center" prop="supplierSpucode" />
        <el-table-column label="含税价"  align="center" prop="taxunitPrice" />
        <el-table-column label="税率"  align="center" prop="taxRate" >
        <template v-slot="scope">
          {{ scope.row.taxRate }} %
        </template>
      </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="productAdd">添加</el-button>
      </span>
    </el-dialog>
    <el-drawer size="60%" :title="show.title" :visible.sync="show.open">
      <div>
        <div style="margin-left:20px ">
          <el-card shadow="never" style="margin: 15px 0 20px 0">
            <div class="operate-container" >
              <span style="margin-left: 20px" class="color-danger">申请单状态：
                <el-tag prop="status" v-for="(item, index) in statusOptions"    v-if="form.status==item.dictValue">{{item.dictLabel}}</el-tag>
              </span>
            </div>
            <el-descriptions :column="3" border style="margin:20px 0 0 0 ">
            <el-descriptions-item label="申请数量"  >
              {{ form.planNum }}
            </el-descriptions-item>
            <el-descriptions-item label="已下采购" >
                {{ form.alreadyNum }}
            </el-descriptions-item>
            <el-descriptions-item label="未下采购"  >
              {{ form.waitNum }}        
            </el-descriptions-item>
            </el-descriptions>            
          </el-card>
        </div>
      </div>
      <div>
        <div style="margin-left:20px ">
          <span class="font-small">申请单基本信息</span>
        </div>
        <el-descriptions :column="3" border style="margin:20px 20px ">
            <el-descriptions-item label="采购申请单号"  >
              {{ form.code }}
            </el-descriptions-item>
            <el-descriptions-item label="要求收货仓库" >
              {{ form.warehouseName }}
            </el-descriptions-item>
            <el-descriptions-item label="要求到货时间"  >
              {{ form.expectedTime }}
            </el-descriptions-item>
            <el-descriptions-item label="创建时间"  >
              {{ form.createTime }}
            </el-descriptions-item>
            <el-descriptions-item label="审核时间"  >
              {{ form.auditTime }}
            </el-descriptions-item>
            <el-descriptions-item label="备注"  >              
              {{form.mark}}             
            </el-descriptions-item>
      </el-descriptions>
      </div>
      <div>
        <div style="margin-left:20px ">
          <span class="font-small">申请单商品是信息</span>
        </div>
        <el-table border :data="selectProducts" v-model="form.products" style="margin:20px 20px">
        <el-table-column label="序号"  width="55" type="index" align="center" /> 
        <el-table-column label="商品图片" align="center">
        <template slot-scope="scope">
          <el-popover
            placement="right"
            title=""
            trigger="hover"
          >
            <img slot="reference" :src="scope.row.image" width="50">
            <img :src="scope.row.image" style="max-width: 150px;">
            </el-popover>
          </template>
        </el-table-column>       
        <el-table-column label="要求供应商"  align="center" prop="supplierName" />
        <el-table-column label="商品编码"  align="center" prop="spuCode" />
        <el-table-column label="商品名称"  align="center" prop="spuName" />
        <el-table-column label="SKU编码"  align="center" prop="skuCode" />
        <el-table-column label="SKU名称" align="center" prop="skuName" />
        <el-table-column label="申请数量" align="center" prop="planNum"/>
        <el-table-column label="已下采购" align="center" prop="alreadyNum"/>        
      </el-table>
      </div>
    </el-drawer>
    
  </div>
</template>

<script>
import { listApply, getApply, delApply, addApply, updateApply, exportApply ,listProduct,updateApplyStatus} from "@/api/oms/apply";
import {listWarehouse} from "@/api/oms/warehouse";
export default {
  name: "Apply",
  data() {
    return {
      dialogVisible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购申请单表格数据
      applyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态 0待审核  1已审核待采购 2部分采购 3已完成 4已取消字典
      statusOptions: [],
      warehouseOptions:[],
      productOptions:[],
      selectProducts:[],
      selection:[],
      selectStatus:{},
      show:{
        open:false,
        title:"采购申请单请详情"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taxRate:null,
        code: null,
        warehouseId: null,
        expectedTime: null,
        auditTime: null,
        status: null,
        actuallyNum: null,
        products: null,
        auditUserId: null,
        planNum: null,
        alreadyNum: null,
        waitNum: null,
        createUserId: null,
       
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        warehouseName: [
          { required: true, message: "要求收货仓库不能为空", trigger: "blur" }
        ],
        expectedTime: [
          { required: true, message: "要求收货时间不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getproductList();
    this.getWarehoues();
    this.getList();
    this.getDicts("oms_purchase_apply_status").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    removeSelected(index) {
      this.selectProducts.splice(index, 1);
    },
    selectWarehouse(){   
      console.log('warehouseOptions',this.warehouseOptions)
      const item = this.warehouseOptions.find(item1=> item1.warehouseName === this.form.warehouseName)
      console.log(item)
      this.form.warehouseId = item.warehouseId
    },
    productAdd(){
     // 获取 dataList 中选中的数据
     const selectedRows = this.$refs.dataList.selection;
      // 遍历选中的数据，添加到 selectedList 列表
      selectedRows.forEach(row => {
        // 判断 selectedData 中是否已存在该行数据
        const index = this.selectProducts.findIndex(item => item.spuCode === row.spuCode && item.supplierCode === row.supplierCode)
        if (index === -1) {
          this.selectProducts.push(row)
        }
      })
      this.dialogVisible=false;
    },
  
    /** 查询采购申请单列表 */
    getList() {
      this.loading = true;
      listApply(this.queryParams).then(response => {
        this.applyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    showDialog() {
      this.dialogVisible = true;
    },
    getproductList() { 
      this.loading = true;     
      listProduct(this.queryParams).then(response =>{
        this.productOptions = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getWarehoues() {      
      listWarehouse(this.queryParams).then(response =>{
        this.warehouseOptions = response.rows;
      });
    },
    // 状态 0待审核  1已审核待采购 2部分采购 3已完成 4已取消字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.selectProducts = [];
      this.form = {
        id: null,
        code: null,
        warehouseId: null,
        expectedTime: null,
        auditTime: null,
        status: 0,
        actuallyNum: null,
        products: null,
        auditUserId: null,
        planNum: null,
        alreadyNum: 0,
        waitNum: null,
        createUserId: null,
        createTime: null,
        updateTime: null,
        remark: null,
        image: null,
        spuCode: null,
        spuName:null,
        skuCode: null,
        skuName: null,
        supplierCode:null,
        supplierName:null,
      };
      this.resetForm("form");
    },
    handleDetails(row){
      this.show.open=true;
      const id = row.id || this.ids
      getApply(id).then(response => {
        this.form = response.data;
        this.selectProducts = response.selectProucts;
      });
    },
    /** 搜索按钮操作 */
    handleQuerys() {
      this.queryParams.pageNum = 1;
      this.getproductList();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    resetQuerys(){
      this.resetForm("queryForm");
      this.handleQuerys;
    },
    // 多选框选中数据
    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.title = "添加采购申请单";
    },
    //审核按钮
    handleUpdateStatus(row){
    this.selectStatus.id = row.id;
    if(row.status == 0){
      this.selectStatus.status = 1;
    };
     if(row.status == 1){
      this.selectStatus.status = 2;
    };
    if(row.status == 2){
      this.selectStatus.status = 3;
    };
    const selectStatus = this.selectStatus;
    const code = row.code;
    this.$confirm('是否确认审核采购申请单号为"' + code + '"的申请单?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return updateApplyStatus(selectStatus)
        }).then(response => {
        if (response.code === 200) {
          this.msgSuccess("修改成功");
          this.getList();
          }
      }).catch(function() {});      
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getApply(id).then(response => {
        this.form = response.data;
        this.selectProducts = response.selectProucts;
        this.open = true;
        this.title = "修改采购申请单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      const data = this.selectProducts;
      const jsonData = JSON.stringify(data);
      this.form.products = jsonData;
      this.form.planNum = this.selectProducts.reduce((total, item) => total + item.planNum, 0);
      this.form.alreadyNum = this.selectProducts.reduce((total, item) => total + item.alreadyNum, 0);
      this.form.waitNum = this.form.planNum - this.form.alreadyNum;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateApply(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addApply(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除采购申请单编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delApply(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有采购申请单数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportApply(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    }
  }
};
</script>

<style scoped>
.order-content{
  margin: 10px;
  
}
 
.operate-container {
  background: #F2F6FC;
  height: 60px;
  margin: -20px -20px 0;
  line-height: 60px;
}


 



</style> 
