<template>
  <div class="app-container">
    <div v-show="viewState == 1">
      <button-bar ref="btnbar" view-title="采购订单审核管理" :btndisabled="btndisabled" @btnhandle="btnHandle" />
      <div class="main-content">
        <div class="searchcon">
          <el-button size="small" class="searchbtn" @click="clicksearchShow">
            {{ searchxianshitit }}
          </el-button>
          <div v-show="isSearchShow" class="search">
            <el-form :inline="true" class="tab-header">
              <el-form-item label="业务日期">
                <el-date-picker v-model="queryParams.params.createStartTime" type="date" placeholder="选择日期"
                  format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width: 200px;">
                </el-date-picker>至
                <el-date-picker v-model="queryParams.params.createEndTime" type="date" placeholder="选择日期"
                  format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width: 200px;">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="供应商">
                <el-select v-model="queryParams.params.supplierSid" clearable placeholder="请选择供应商"
                  style="width: 220px;">
                  <el-option v-for="item in supplierList" :key="item.sid" :label="item.supplierName" :value="item.sid">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="仓库">
                <el-select v-model="queryParams.params.wareHouseSid" placeholder="请选择仓库" style="width: 220px;">
                  <el-option v-for="item in warehouseList" :key="item.sid" :label="item.warehouseName"
                    :value="item.sid" />
                </el-select>
              </el-form-item>
              <el-form-item label="收货状态">
                <el-select v-model="queryParams.params.receiveStateKey" placeholder="请选择" style="width: 220px;">
                  <el-option v-for="(item,i) in receiveStateList" :key="i" :label="item.dictValue"
                    :value="item.dictKey">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="物流单号">
                <el-input v-model="queryParams.params.logisticsNum" placeholder="" clearable />
              </el-form-item>
              <el-form-item label="单据编号">
                <el-input v-model="queryParams.params.billNo" placeholder="" clearable />
              </el-form-item>
              <!-- <el-form-item label="制单人">
                <el-input v-model="queryParams.params.createByName" placeholder="" clearable />
              </el-form-item> -->
              <el-form-item label="业务员">
                <el-input v-model="queryParams.params.purchaserName" placeholder="" clearable />
              </el-form-item>
              <el-form-item label="商品">
                <el-select v-model="queryParams.params.goodsSid" placeholder="请选择" style="width: 220px;">
                  <el-option v-for="(item,i) in goodsList" :key="i" :label="item.title" :value="item.sid">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="queryParams.params.remarks" placeholder="" clearable />
              </el-form-item>
              <!-- <el-form-item label="收货状态">
                <el-select v-model="queryParams.params.receiveStateKey" placeholder="请选择" style="width: 220px;">
                  <el-option v-for="(item,i) in receiveStateList" :key="i" :label="item.dictValue"
                    :value="item.dictKey">
                  </el-option>
                </el-select>
              </el-form-item> -->
              <el-form-item label="发货状态">
                <el-select v-model="queryParams.params.deliveryStateKey" placeholder="请选择" style="width: 220px;">
                  <el-option v-for="(item,i) in deliveryStateList" :key="i" :label="item.dictValue"
                    :value="item.dictKey">
                  </el-option>
                </el-select>
              </el-form-item>

            </el-form>
            <div class="btn" style="text-align: center;">
              <el-button type="primary" size="small" icon="el-icon-search" @click="dosearch">查询</el-button>
              <el-button type="primary" size="small" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            </div>
          </div>
        </div>
        <!-- Start 项目列表头部 -->
        <div class="listtop">
          <div class="tit">采购订单审核列表</div>
          <pagination v-show="dataList.length > 0" :total="queryParams.total" :page.sync="queryParams.current"
            :limit.sync="queryParams.size" class="pagination" @pagination="loadList" />
        </div>
        <!-- End 项目列表头部 -->
        <!-- Start 项目列表 -->
        <div class="">
          <el-table v-loading="tableLoading" :data="dataList" border style="width: 100%"
            @selection-change="selectionLineChangeHandle" @row-click="rowItemClick" show-summary
            :summary-method="getSummaries">
            <el-table-column fixed width="80" type="selection" align="center" />
            <el-table-column fixed width="60" label="序号" type="index" :index="indexMethod" align="center" />
            <el-table-column fixed label="操作" align="center" width="80">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="toRelevancy(scope.row)">查看</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="业务日期" width="120" align="center" />
            <el-table-column prop="billNo" label="单据编号" width="120" align="center" />
            <el-table-column prop="supplierName" label="供应商" width="150" align="center" />
            <el-table-column prop="purchaserName" label="业务员" width="120" align="center" />
            <el-table-column prop="wareHouseName" label="仓库" width="150" align="center" />
            <el-table-column prop="nodeState" label="状态" width="120" align="center" />
            <el-table-column prop="state" label="审核进度" width="120" align="center" />
            <el-table-column prop="amountTotal" label="商品总额" width="120" align="center" />
            <el-table-column prop="thisPayAmount" label="本次付款" width="120" align="center" />
            <el-table-column prop="taxAmount" label="税额汇总" width="120" align="center" />
            <el-table-column prop="countTotal" label="商品数量" width="120" align="center" />
            <el-table-column prop="remarks" label="备注" width="200" align="center" />
            <el-table-column prop="createByName" label="创建人" align="center" />
            <el-table-column prop="modifyTime" label="最后修改时间" width="150" align="center" />
          </el-table>
        </div>
        <!-- End 项目列表 -->
        <!-- <div class="pages">
          <div class="tit" /> -->
        <!--  翻页  -->
        <!--  <pagination v-show="dataList.length > 0" :total="queryParams.total" :page.sync="queryParams.current"
            :limit.sync="queryParams.size" class="pagination" @pagination="loadList" />
        </div> -->

        <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect"
          text-color="#666" active-text-color="white">

          <el-menu-item index="1">采购明细</el-menu-item>
          <!-- <el-menu-item index="2">费用/预付款</el-menu-item> -->
          <!-- <el-menu-item index="3">附 件</el-menu-item> -->
          <el-menu-item index="4">操作日志</el-menu-item>
        </el-menu>

        <div v-show="activeIndex=='1'" style="margin-bottom: 50px;">
          <el-table :data="goodsDetailList" border style="width: 100%">
            <el-table-column width="60" label="序号" type="index" :index="indexMethod" align="center" />
            <el-table-column prop="goodsSkuTitle" label="商品名称" width="120" align="center" />
            <el-table-column prop="goodsSkuCode" label="商品编码" width="120" align="center" />
            <el-table-column prop="goodsSkuOwnSpec" label="规格型号" width="120" align="center" />
            <el-table-column prop="unit" label="单位" align="center" />
            <el-table-column prop="count" label="数量" width="120" align="center" />
            <el-table-column label="数量(pcs)" prop="pcsCount" align="center" width="150" />
            <el-table-column label="已入库数量" prop="pcsNum" align="center" width="150" />
            <el-table-column label="已发货数量" prop="pcsNum" align="center" width="150" />
            <el-table-column label="已入库(pcs)" prop="pcsNum" align="center" width="150" />
            <el-table-column label="待入库数量" prop="pcsNum" align="center" width="150" />
            <el-table-column label="待入库(pcs)" prop="pcsNum" align="center" width="150" />
            <el-table-column label="吊牌价" prop="tagPrice" width="120" align="center" />
            <el-table-column label="单价" prop="cost" width="120" align="center" />
            <el-table-column prop="discountRate" label="折扣率(%)" width="120" align="center" />
            <el-table-column prop="discountPrice" label="折扣单价" width="120" align="center" />
            <el-table-column prop="shareAmount" label="分摊金额" width="150" align="center" />
            <el-table-column prop="amount" label="总价" width="120" align="center" />
            <el-table-column prop="taxRate" label="税率" width="120" align="center" />
            <el-table-column prop="unTaxPrice" label="未含税价" width="120" align="center" />
            <el-table-column prop="taxAmount" label="总税额" width="120" align="center" />
            <el-table-column prop="unTaxTotalAmount" label="未含总税价" width="120" align="center" />
            <el-table-column prop="cycle" label="采购周期" width="120" align="center" />
            <el-table-column prop="deliveryDate" label="预计到货日期" width="180" align="center" />
            <el-table-column prop="madeDate" label="生产日期" width="180" align="center" />
            <el-table-column prop="expireDate" label="过期日期" width="120" align="center" />
            <el-table-column prop="batchNumber" label="批次号" width="200" align="center" />
            <el-table-column label="3天" align="center">
              <el-table-column prop="realCount" label="平均销量" align="center" width="100" />
              <el-table-column prop="realAmount" label="剩余天数" align="center" width="100" />
              <el-table-column prop="realAmount" label="销售总览" align="center" width="100" />
            </el-table-column>
            <el-table-column label="7天" align="center">
              <el-table-column prop="realCount" label="平均销量" align="center" width="100" />
              <el-table-column prop="realAmount" label="剩余天数" align="center" width="100" />
              <el-table-column prop="realAmount" label="销售总览" align="center" width="100" />
            </el-table-column>
            <el-table-column label="15天" align="center">
              <el-table-column prop="realCount" label="平均销量" align="center" width="100" />
              <el-table-column prop="realAmount" label="剩余天数" align="center" width="100" />
              <el-table-column prop="realAmount" label="销售总览" align="center" width="100" />
            </el-table-column>
            <el-table-column label="30天" align="center">
              <el-table-column prop="realCount" label="平均销量" align="center" width="100" />
              <el-table-column prop="realAmount" label="剩余天数" align="center" width="100" />
              <el-table-column prop="realAmount" label="销售总览" align="center" width="100" />
            </el-table-column>
            <el-table-column prop="itemNumber" label="实际库存" width="120" align="center" />
            <el-table-column prop="itemNumber" label="可用库存" width="120" align="center" />
            <el-table-column prop="itemNumber" label="在途库存" width="120" align="center" />
            <el-table-column prop="itemNumber" label="货号" width="120" align="center" />
            <el-table-column prop="remarks" label="备注" width="120" align="center" />
          </el-table>
        </div>

        <div v-show="activeIndex=='4'" style="margin-bottom: 50px;">
          <el-table :data="operateList" border style="width: 100%">
            <el-table-column width="60" label="序号" type="index" :index="indexMethod" align="center" />
            <el-table-column prop="createTime" label="操作时间" width="250" align="center" />
            <el-table-column prop="createByName" label="操作账号" width="180" align="center" />
            <el-table-column prop="nodeName" label="操作类型" width="180" align="center" />
            <el-table-column prop="result" label="操作结果" align="center" />
          </el-table>
        </div>

      </div>
    </div>
    <!-- End 查询和其列表部分 -->
    <!-- 新增修改部分组件 -->
    <divInfo v-show="viewState == 4" ref="divinfo" @doback="resetState" @reloadlist="loadList" />

    <el-dialog title="审核信息" :visible="dialogVisible" width="50%">
      <el-form ref="" :model="orderInfo" class="formaddcopy02">
        <el-row class="first_row">
          <el-col :span="24">
            <div class="span-sty">审核意见</div>
            <el-form-item>
              <el-radio-group v-model="orderInfo.state" size="small" style="margin-left: 120px;">
                <el-radio :label="2">审核通过</el-radio>
                <el-radio :label="3">审核不通过</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>

          <el-col :span="24">
            <div class="span-sty"> 备注</div>
            <el-form-item>
              <el-input v-model="orderInfo.remarks" placeholder="" class="addinputw addinputInfo" clearable />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="handleSave()">保存</el-button>
        <el-button type="info" size="small" @click="dialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
  import req from '@/api/purchase/purchaseReview.js'
  import ButtonBar from '@/components/ButtonBar'
  import Pagination from '@/components/pagination'
  import pageye from '@/components/pagination/pageye'
  import divInfo from './purchaseOrderInfo.vue'
  import {
    typeValues,
    choiceSupplierInfo,
    getWarehouses,
    getGoodsListAllByOrg
  } from '@/api/Common/dictcommons'
  export default {
    components: {
      ButtonBar,
      Pagination,
      pageye,
      divInfo
    },
    data() {
      return {
        activeIndex: '1',
        dialogVisible: false,
        btndisabled: false,
        viewState: 1, // 1、列表 2、添加 3、修改 4、查看
        isSearchShow: false,
        searchxianshitit: '显示查询条件',
        tableLoading: false,
        dataList: [],
        formobj: {
          purchaseBillAmount: {
            freight: ""
          },
          purchaseAppendixList: [],
          purchaseBillDetailList: {}
        },
        orderInfo: {},
        btnList: [{
            type: 'primary',
            size: 'small',
            icon: 'submit',
            btnKey: 'toSubmit',
            btnLabel: '确认审核'
          },
          {
            type: 'info',
            size: 'small',
            icon: 'cross',
            btnKey: 'doClose',
            btnLabel: '关闭'
          }
        ],
        queryParams: {
          current: 1,
          size: 10,
          total: 0,
          params: {
            "supplierName": "",
            "supplierSid": "",
            "wareHouseName": "",
            "wareHouseSid": "",
            "receiveStateKey": "",
            "logisticsNum": "",
            "deliveryStateKey": "",
            "billNo": "",
            "purchaserName": "",
            "remarks": "",
            "createStartTime": "",
            "createEndTime": "",
            "orgLevelKey": "",
            "menuUrl": "",
            "orgPath": "",
            "userSid": "",
            "goodsSid": ""
          }
        },
        sids: [],
        selectionList: [],
        receiveStateList: [],
        deliveryStateList: [],
        warehouseList: [],
        supplierList: [],
        goodsList: [],
        rowItemSid: '',
        goodsDetailList: [],
        operateList: [],

      }
    },
    mounted() {
      this.$refs['btnbar'].setButtonList(this.btnList)
    },
    created() {

      this.init()
      this.loadList()

    },
    methods: {

      init() {

        typeValues({
          type: 'receiveState'
        }).then((res) => {
          if (res.success) {
            this.receiveStateList = res.data
          }
        })

        typeValues({
          type: 'deliveryState'
        }).then((res) => {
          if (res.success) {
            this.deliveryStateList = res.data
          }
        })

        choiceSupplierInfo({
          createOrgSid: window.sessionStorage.getItem('orgSid')
        }).then((resp) => {
          if (resp.success) {
            this.supplierList = resp.data
            console.log("aaaaaa", this.supplierNameList);
          }
        })
        getWarehouses({
          orgPath: window.sessionStorage.getItem('orgSidPath'),
        }).then((res) => {
          if (res.success) {
            this.warehouseList = res.data

            console.log("aaaaaa", this.warehouseList);

          }
        })

        getGoodsListAllByOrg({
          orgPath: window.sessionStorage.getItem('orgSidPath'),
        }).then((res) => {
          if (res.success) {
            this.goodsList = res.data

            console.log("aaaaaa", this.goodsList);

          }
        })

      },

      // 合计
      getSummaries(param) {
        const {
          columns,
          data
        } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '总计：'
            return
          }
          const values = data.map(item => Number(item[column.property]))
          if (column.property === 'amountTotal') { //商品总额
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] += ''
          } else if (column.property === 'freight') { //采购运费
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] += ''
          } else if (column.property === 'otherAmount') { //其他费用
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] += ''
          } else if (column.property === 'prepayment') { //总税额
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] += ''
          } else if (column.property === 'productProgress') { //未含税总额
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] += ''
          } else if (column.property === 'countTotal') { //总采购数量
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] += ''
          } else if (column.property === 'countTotal') { // 已入库数量
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] += ''
          } else if (column.property === 'countTotal') { //已入库金额
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] += ''
          }
        })
        return sums
      },

      rowItemClick(row) {

        console.log("row", row);
        this.rowItemSid = row.sid
        this.handleSelect(this.activeIndex)
      },
      handleSelect(val) {
        console.log("val", val);
        this.activeIndex = val

        if (val == '1') { // 采购明细
          req.fetchDetailsBySid(this.rowItemSid).then((resp) => {
            this.goodsDetailList = resp.data.purchaseBillDetailList
          }).catch(() => {})
        }

        if (val == '4') { // 操作记录
          var parpams = {
            sid: this.rowItemSid
          }
          req.operationrecordDetails(parpams).then((resp) => {
            this.operateList = resp.data
          }).catch(() => {})
        }

      },
      selectionLineChangeHandle(val) {
        console.log("val", val);

        this.selectionList = val

        const aa = []
        val.forEach(element => {
          aa.push(element.sid)
        })
        this.sids = aa
      },
      // 搜索条件效果
      clicksearchShow() {
        this.isSearchShow = !this.isSearchShow
        if (this.isSearchShow) {
          this.searchxianshitit = '隐藏查询条件'
        } else {
          this.searchxianshitit = '显示查询条件'
        }
      },
      btnHandle(btnKey) {
        switch (btnKey) {
          case 'toSubmit':
            this.toSubmit()
            break
          case 'toAdd':
            this.toAdd()
            break
          case 'toEdit':
            this.toEdit()
            break
          case 'doDel':
            this.doDel()
            break
          case 'doClose':
            this.doClose()
            break
          default:
            break
        }
      },
      loadList() {
        this.tableLoading = true
        this.queryParams.params.userSid = window.sessionStorage.getItem('userSid')
        this.queryParams.params.orgPath = window.sessionStorage.getItem('orgSidPath')
        this.queryParams.params.menuUrl = this.$route.path
        req.listPage(this.queryParams).then((resp) => {
          this.tableLoading = false
          if (resp.success) {
            const data = resp.data
            this.queryParams.total = data.total
            this.dataList = data.records
            this.rowItemSid = data.records[0].sid
            this.handleSelect('1')
          } else {
            // 根据resp.code进行异常情况处理
            this.dataList = []
            this.queryParams.total = 0
          }
        }).catch(() => {
          this.tableLoading = false
        })
      },

      // 序号
      indexMethod(index) {
        var pagestart = (this.queryParams.current - 1) * this.queryParams.size
        var pageindex = index + 1 + pagestart
        return pageindex
      },
      dosearch() {
        this.queryParams.current = 1
        this.loadList()
      },
      resetQuery() {
        this.queryParams = {
          current: 1,
          size: 10,
          total: 0,
          params: {
            "supplierName": "",
            "supplierSid": "",
            "wareHouseName": "",
            "wareHouseSid": "",
            "receiveStateKey": "",
            "logisticsNum": "",
            "deliveryStateKey": "",
            "billNo": "",
            "purchaserName": "",
            "remarks": "",
            "createStartTime": "",
            "createEndTime": "",
            "orgLevelKey": "",
            "menuUrl": "",
            "orgPath": "",
            "userSid": "",
            "goodsSid": ""
          }
        }
        this.loadList()
      },
      toSubmit() {
        if (this.sids.length > 0) {
          this.dialogVisible = true
        } else {
          this.$message({
            type: 'warning',
            showClose: true,
            message: '请选择一条记录进行操作'
          })
        }
      },
      toAdd() {
        this.viewState = 2
        this.$refs['divadd'].showAdd()
      },
      toEdit() {

        if (this.selectionList.length != 1) {
          this.$message({
            type: 'warning',
            message: "请选择一条数据。",
            showClose: true
          })
          return
        }

        this.viewState = 3
        this.$refs['divadd'].showEdit(this.selectionList[0])
      },

      doClose() {
        this.$store.dispatch('tagsView/delView', this.$route)
        this.$router.go(-1)
      },
      toRelevancy(row) {
        this.viewState = 4
        this.$refs['divinfo'].showAdd(row)
      },
      doDel() {

        if (this.sids.length > 0) {
          const tip = '请确认是否删除所选 ' + this.sids.length + ' 条记录?'
          this.$confirm(tip, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            const loading = this.$loading({
              lock: true,
              text: 'Loading',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            })
            req.deleteBySids(this.sids).then((resp) => {
              loading.close()
              if (resp.success) {
                this.$message({
                  type: 'success',
                  message: resp.msg,
                  showClose: true
                })
                this.loadList()
              } else {
                // 根据resp.code进行异常情况处理
              }
            }).catch(e => {
              loading.close()
            })
          }).catch(() => {})
        } else {
          this.$message({
            showClose: true,
            message: '请至少选择一条记录进行删除操作'
          })
        }
      },
      resetState() {
        this.viewState = 1
      },
      handleSave() {

        this.orderInfo.sid = this.sids[0]

        req.examine(this.orderInfo).then((resp) => {
          if (resp.success) {
            this.$message({
              type: 'success',
              message: resp.msg,
              showClose: true
            })
            this.dialogVisible = false
            this.loadList()
          } else {
            // 根据resp.code进行异常情况处理
          }
        }).catch(e => {})

      }

    }
  }
</script>
<style scoped>
  /deep/ .el-form-item__error {
    margin-left: 120px !important;
  }

  .must {
    color: #f00;
  }

  .span-sty {
    width: 130px !important;
  }

  .addinputInfo {
    margin-left: 120px !important;
  }

  .formaddcopy02 .el-row .el-col /deep/ .el-form-item .addinputw {
    margin-left: 120px !important;
    width: calc(100% - 115px);
  }

  .first_row {
    border-top: 1px solid #E0E3EB;
  }

  .titleOne {
    padding: 7px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
  }

  .el-radio /deep/ .el-radio__label {

    font-size: 14px !important;

  }

  .el-menu-item.is-active {
    background-color: #3370ff !important;
    color: #fff;

    span {
      color: #fff;
    }
  }

  .el-submenu__title.is-active {
    background: #1c88cf !important;
    color: #fff !important;
  }
</style>
