<template>
  <div class="app-container">
    <div class="filter-container">

      <el-input size="mini" v-model="search.keyWord" placeholder="关键字" style="width: 200px;" class="filter-item" />
      <el-button size="mini" class="filter-item" type="primary" icon="el-icon-search" @click="searchData">
        搜索
      </el-button>

      <el-button
        v-if="webType && isChoose == false"
        class="filter-item"
        style="margin-left: 10px;"
        size="mini"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreateAdd">
        增加辅料档案
      </el-button>
      <el-checkbox v-if="!isChoose" size="mini" @change="checkDisable" v-model="disableLock" label="已禁用" border></el-checkbox>
      <div class="top-right-btn">
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button size="mini" circle icon="el-icon-refresh" @click="getPaperInfo" />
        </el-tooltip>
      </div>
    </div>

    <el-table
      :data="tableData"
      v-loading="listLoading"
      style="width: 100%;margin-bottom: 20px;"
      row-key="id"
      border
      default-expand-all>
      <el-table-column
        prop="materialCode"
        label="辅料编码">
      </el-table-column>
      <el-table-column
        prop="materialTypeName"
        label="辅料分类名称">
      </el-table-column>
      <el-table-column
        width="300px"
        prop="materialName"
        label="辅料名称">
      </el-table-column>
     <el-table-column
        label="品牌"
        prop="mtModel"
      >
      </el-table-column>
      <el-table-column
        prop="mtRule"
        label="规格">
      </el-table-column>
      <el-table-column align="center" label="状态" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag v-if="row.voidFlag==0" type="success">
            启用
          </el-tag>
          <el-tag v-else-if="row.voidFlag==1" type="danger">
            禁用
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="left" align="center" :width="isChoose?80:380" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <template v-if="webType">
            <template v-if="!isChoose">
              <el-button @click="handleUpdate(row)" type="primary" size="mini">
                编辑
              </el-button>
              <el-button @click="handleUpdatePrecise(row)" type="primary" size="mini">
                修改库存精度
              </el-button>
              <el-button v-if="permissionFlag" @click="handleStock(row)" type="warning" size="mini">
                库存盘点
              </el-button>
              <el-button @click="editStatus(row.id,'1')" type="danger" v-if="row.voidFlag==0" size="mini">
                禁用
              </el-button>
              <el-button @click="editStatus(row.id,'0')" v-else-if="row.voidFlag==1" size="mini">
                启用
              </el-button>
            </template>
            <template v-else>
              <el-button @click="sourceType == 1? chooseThisTo(row):chooseThis(row)" type="primary" size="mini">
                选择
              </el-button>
            </template>
          </template>
          <template v-else>
            <el-button @click="ERPChoose(row)" type="primary" size="mini">
              选择
            </el-button>
          </template>
        </template>
      </el-table-column>

    </el-table>
    <pagination v-show="listData.total>0" :total="listData.total" :page.sync="listData.page" :limit.sync="listData.pageSize" @pagination="getPaperInfo" />

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="800px">
      <el-form label-width="100px" label-position="right">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="辅料名称">
              <el-input v-model="form.materialName" :disabled="dialogStatus==2"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格">
              <el-input v-model="form.mtRule"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="辅料分类">
              <el-select v-model="form.idMaterialType" filterable placeholder="请选择">
                <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.materialTypeName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌">
              <el-input v-model="form.mtModel"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购单位">
              <el-input v-model="form.byUnit"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购=>库存">
              <el-input type="number" v-model="form.convertUnitByToMt"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存单位">
              <el-input v-model="form.mtUnit"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存=>使用">
              <el-input type="number" v-model="form.convertUnitMtToSe"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="使用单位">
              <el-input v-model="form.seUnit"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机台必选">
              <el-radio :label="1" v-model="form.machineRequestFlag">是</el-radio>
              <el-radio :label="0" v-model="form.machineRequestFlag">否</el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计价方式">
              <el-select v-model="form.priceType">
                <el-option label="单价" :value="0"></el-option>
                <el-option label="平方价" :value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="条形码">
              <el-input v-model="form.barCode"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存精度">
              <el-input-number v-model="form.stockPrecision" :disabled="dialogStatus==2"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="备注">
              <el-input type="textarea" :rows="2" v-model="form.remark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogStatus==='1'?addBtn():editBtn()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="修改库存精度" :visible.sync="updateVisible">
      <el-form>
        <el-form-item label="库存精度">
          <el-input-number v-model="updateInfo.stockPrecision"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateVisible = false">取 消</el-button>
        <el-button type="primary" @click="updatePreciseBtn">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="库存盘点" :visible.sync="stockVisible">
      <el-form size="mini" inline>
        <el-form-item label="分厂">
          <el-select v-model="stockSearch.idCompany">
            <el-option
              v-for="(item,index) in companyList"
              :key="index"
              :value="item.id"
              :label="item.companyName"></el-option>
          </el-select>
        </el-form-item>
        <el-button size="mini" type="primary" @click="getStockData">搜索</el-button>
      </el-form>
      <el-table size="mini" border :data="stockData">
        <el-table-column label="库房" prop="stockRoomName"></el-table-column>
        <el-table-column label="数量" prop="stockQty">
          <template slot-scope="{row}">
            <el-input size="mini" v-model="row.stockQty"></el-input>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="stockVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveStock">确 定</el-button>
      </div>
    </el-dialog>
    <cancledialog @tableRefresh="tableRefresh" ref="confirmDialog"></cancledialog>
  </div>
</template>

<script>
import {
  getMaterialInfoList,
  getMaterialInfoById,
  updateMaterialInfo,
  addMaterialInfo,
  updateMaterialStockPrecise,
  getMaterialCompanyQtyInfo, saveMaterialCompanyQtyInfo
} from '@/api/baseInfo/accessories/accessoriesInfo.js'
import { getMaterialTypeList } from '@/api/baseInfo/accessories/accessoriesType.js'
import Cancledialog from '@/components/Dialog/Cancledialog.vue'
import {getCompanyList} from "@/api/stock/paperInventory";
import {ifPermission} from "@/api/order/orderList";

const form = {
  mtRule: '',
  paperCode: '',
  mtModel: '',
  byUnit: '',
  mtUnit: '',
  seUnit: '',
  barCode: '',
  remark: '',
  materialName: '',
  materialCode: '',
  idMaterialType: '',
  materialTypeName: '',
  convertUnitByToMt: 1,
  convertUnitMtToSe: 1,
  stockPrecision: 3,
  priceType: 0,
  machineRequestFlag: 0
}
export default {
  components: {
    Cancledialog
  },
  props: {
    isChoose: {
      type: Boolean,
      default: false
    },
    /**
     * 调用来源
     * 0 普通调用
     * 1 查询统计调用
     */
    sourceType: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      disableLock: false,
      webType: true,
      permissionFlag: false,
      dialogStatus: 1, // 1增加，2修改
      dialogTitle: '',
      dialogVisible: false,
      updateVisible: false,
      stockVisible: false,
      search: {
        keyWord: '',
        voidFlag:'',
      },
      form: Object.assign({}, form),
      options: [],

      listData: {
        total: 0,
        page: 1,
        pageSize: 10
      },
      updateInfo: {
        id: '',
        stockPrecision: null
      },
      confirmdialog: false,
      listLoading: false,
      tableData: [],

      stockSearch: {
        idCompany: '',
        idMaterial: ''
      },
      companyList:[],
      stockData: []
    }
  },
  mounted() {
    this.checkPermission('stock:material:check')
    this.getPaperInfo()
    this.getMaterialTypeInfo()
    if (this.$route.query.type === undefined) {
      this.webType = true
    } else {
      this.webType = false
    }
    // console.log(this.webType)
  },
  methods: {
    checkDisable(val) {
      // console.log(val);
      this.listData.page = 1;
      this.getPaperInfo()
    },
    // 判断权限
    checkPermission(permissionStr) {
      const _that = this
      var data = {
        permission: permissionStr
      }
      ifPermission(data).then(res => {
        // console.log(res)
        if (res.data == 1) {
          // if (permissionStr == 'stock:material:check') {
            _that.permissionFlag = true
          // }
        }
      })
    },
    // 获取列表
    getPaperInfo() {
      const _that = this
      _that.listLoading = true;
      if(_that.disableLock){
        _that.search.voidFlag = 1;
      }else {
        _that.search.voidFlag = 0;
      }
      var params = _that.search
      var page = {
        pageIndex: _that.listData.page,
        pageSize: _that.listData.pageSize
      }
      var data = {
        'params': JSON.stringify(params),
        'page': JSON.stringify(page)
      }
      // console.log(data);
      getMaterialInfoList(data).then(response => {
        // console.log(response)
        const data = response.data
        // //  组合表单数据
        _that.tableData = data
        _that.listData.total = response.total
        // console.log(_that.tableData)
        _that.listLoading = false
      }).catch(err => {
        _that.$message.error(err)
        _that.listLoading = false
      })
    },

    // 获取分类列表
    getMaterialTypeInfo() {
      const _that = this
      var data = {
        'params': JSON.stringify({
          'voidFlag': 0
        })
      }
      // console.log(data);
      getMaterialTypeList(data).then(response => {
        // console.log(response)
        const data = response.data
        _that.options = data
      }).catch(err => {

      })
    },
    // 增加机型档案
    handleCreateAdd() {
      // 增加系统目录
      const _that = this
      _that.form = Object.assign({}, form)
      _that.dialogTitle = '增加辅料档案'
      _that.dialogStatus = '1'
      _that.dialogVisible = true
    },
    // 刷新变革
    tableRefresh() {
      // 刷新变革
      this.getPaperInfo()
    },
    // 增加机型档案
    addBtn() {
      const _that = this
      var info = JSON.stringify(_that.form)
      var data = {
        'info': info
      }
      // console.log(data);
      // return

      addMaterialInfo(data).then(res => {
        // console.log(res);
        if (res.httpCode === 200) {
          _that.dialogVisible = false
          _that.$message({
            message: '增加成功',
            type: 'success'
          })
          _that.tableRefresh()
        } else {
          _that.$message.error(res.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
        _that.dialogVisible = true
      })
    },

    // 唤起修改
    handleUpdate(row) {
      const _that = this
      _that.form = Object.assign({}, form)

      _that.dialogTitle = '修改辅料档案'
      _that.dialogVisible = true
      _that.dialogStatus = '2'

      var idPrint = row.id
      var data = {
        id: idPrint
      }

      getMaterialInfoById(data).then(res => {
        // console.log(res)
        const data = res.data

        _that.form = {
          id: data.id,
          materialName: data.materialName,
          materialCode: data.materialCode,
          mtRule: data.mtRule,
          idMaterialType: data.idMaterialType,
          materialTypeName: data.materialTypeName,
          paperCode: data.paperCode,
          mtModel: data.mtModel,
          byUnit: data.byUnit,
          mtUnit: data.mtUnit,
          seUnit: data.seUnit,
          barCode: data.barCode,
          remark: data.remark,
          convertUnitMtToSe: data.convertUnitMtToSe,
          convertUnitByToMt: data.convertUnitByToMt,
          stockPrecision: data.stockPrecision,
          priceType: data.priceType,
          machineRequestFlag: data.machineRequestFlag
        }
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    // 修改机型档案
    editBtn() {
      const _that = this;
      _that.form.materialTypeName = _that.options.find(x=> x.id === _that.form.idMaterialType).materialTypeName;
      var info = JSON.stringify(_that.form)
      var data = {
        'info': info
      }

      updateMaterialInfo(data).then(res => {
        // console.log(res);
        if (res.httpCode == 200) {
          _that.dialogVisible = false
          _that.$message({
            message: '修改成功',
            type: 'success'
          })
          _that.tableRefresh()
        } else {
          _that.$message.error(res.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
        _that.dialogVisible = true
      })
    },

    handleUpdatePrecise(row) {
      const _that = this
      _that.updateVisible = true
      _that.updateInfo = {
        id: row.id,
        stockPrecision: null
      }

      var idPrint = row.id
      var data = {
        id: idPrint
      }

      getMaterialInfoById(data).then(res => {
        // console.log(res)
        const data = res.data

        _that.updateInfo = {
          id: data.id,
          stockPrecision: data.stockPrecision
        }
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    updatePreciseBtn() {
      const _that = this
      var info = JSON.stringify(_that.updateInfo)
      var data = {
        'info': info
      }

      updateMaterialStockPrecise(data).then(res => {
        // console.log(res);
        if (res.httpCode == 200) {
          _that.updateVisible = false
          _that.$message({
            message: '修改成功',
            type: 'success'
          })
          _that.tableRefresh()
        } else {
          _that.$message.error(res.msg)
        }
      }).catch(err => {
        _that.$message.error(err)
        _that.dialogVisible = true
      })
    },

    // 库存盘点
    handleStock(row) {
      const _that = this
      _that.stockVisible = true
      _that.stockSearch.idMaterial = row.id
      _that.getCompanyInfo()
    },

    // 获取分厂列表
    getCompanyInfo() {
      const _that = this
      var data = {}
      getCompanyList(data).then(response => {
        // console.log(response)
        _that.companyList = response.data
        _that.stockSearch.idCompany = _that.companyList[0].id
        _that.getStockData()

      }).catch(err => {
        _that.$message.error(err)
      })
    },
    // 获取库存数据
    getStockData() {
      const _that = this
      var data = _that.stockSearch
      getMaterialCompanyQtyInfo(data).then(response => {
        // console.log(response)
        _that.stockData = response.data


      }).catch(err => {
        _that.$message.error(err)
      })
    },
    saveStock(){
      const _that = this
      var info = []
      _that.stockData.forEach(item =>{
        var infoItem = {
          idMaterial: _that.stockSearch.idMaterial,
          idCompany: _that.stockSearch.idCompany,
          idStockRoom: item.idStockRoom,
          stockQty: item.stockQty
        }
        info.push(infoItem)
      })
      // console.log(info);
      // return
      var data =JSON.stringify(info)
      saveMaterialCompanyQtyInfo(data).then(response => {
        // console.log(response)
        if (response.httpCode == 200) {
          _that.$message.success('保存成功')
          _that.stockVisible = false
          _that.tableRefresh()
        }


      }).catch(err => {
        _that.$message.error(err)
      })
    },

    // 启用禁用
    editStatus(id, status) {
      var _that = this
      var printerTypeInfo = {
        id: id,
        voidFlag: status
      }
      var params = {
        'info': JSON.stringify(printerTypeInfo)
      }

      var url = '/doc/voidMaterialInfo'
      _that.$refs.confirmDialog.updataClick(params, url)
    },

    // 搜索
    searchData() {
      this.listData.page = 1
      this.getPaperInfo()
    },
    chooseThis(row) {
      this.$emit('chooseAccessories', row)
    },

    // 查询统计选择
    chooseThisTo(row) {
      var data = {
        id: row.id,
        name: row.materialName
      }
      this.$emit('chooseRow', data)
    },
    ERPChoose(row) {
      // this.$message.error(row)
      dyERP.sendJson(JSON.stringify(row))
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-checkbox.is-bordered.is-checked {
  border-color: #F56C6C;
}
::v-deep .el-checkbox__input.is-checked .el-checkbox__inner,
::v-deep .el-checkbox__input.is-indeterminate .el-checkbox__inner {
  border-color: #F56C6C !important;
  background-color: #F56C6C !important;
}

::v-deep .el-checkbox__input.is-checked + .el-checkbox__label {
  color: #F56C6C !important;
}

::v-deep .el-checkbox__inner:hover {
  border-color: #F56C6C !important;
}

::v-deep .el-checkbox__input.is-focus .el-checkbox__inner {
  border-color: #F56C6C !important;
}
  .filter-container {
    margin-bottom: 15px;
  }
</style>
