<template>
  <!-- 计量临时委托生成 -->
  <div class="systemBase">
    <div style="margin-top: 10px; border-bottom: 1px solid #d5d5d5">
      <el-form :inline="true">
        <el-form-item label="物资名称" label-width="75px">
          <el-input
            type="text"
            size="mini"
            v-model="searchForm.matterName"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="发货单位" label-width="75px">
          <el-input
            type="text"
            size="mini"
            v-model="searchForm.forwardingUnitName"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="收货单位" label-width="75px">
          <el-input
            type="text"
            size="mini"
            v-model="searchForm.receivingUintName"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="状态" label-width="75px">
          <el-select v-model="searchForm.valueFlag" size="mini">
            <el-option
              v-for="(item, index) in valueFlagList"
              :key="index"
              :label="item.value"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label-width="20px">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-search"
            @click="getDataList(1)"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item label-width="20px">
          <el-button size="mini" type="primary" @click="addDialog"
            >新增</el-button
          >
        </el-form-item>
        <el-form-item label-width="20px">
          <el-button
            icon="el-icon-printer"
            type="primary"
            size="mini"
            @click="printQRCode"
            v-privilege="activeMenu + 'PRINT'"
            >打印二维码</el-button
          >
        </el-form-item>
        <el-form-item label-width="20px">
          <el-button
            icon="el-icon-picture"
            type="primary"
            size="mini"
            @click="generateQRCode"
            v-privilege="activeMenu + 'MAKE'"
            >生成二维码</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <el-card>
      <div class="common-table-div">
        <el-table
          ref="dataTable"
          @current-change="rowChange"
          border
          :height="tableHeight"
          highlight-current-row
          :data="tableData"
          :icore-filter-flag="icoreFilterFlag"
        >
          <el-table-column
            type="index"
            label="序号"
            fixed="left"
            align="center"
          ></el-table-column>
          <!-- <el-table-column
            type="selection"
            width="55"
            fixed="left"
            align="center"
          ></el-table-column> -->
          <el-table-column
            sortable
            :show-overflow-tooltip="true"
            min-width="100px"
            prop="entrustNo"
            label="临时委托号"
            align="center"
          ></el-table-column>
          <el-table-column
            sortable
            :show-overflow-tooltip="true"
            min-width="160px"
            prop="matterName"
            label="物料名称"
            align="center"
          ></el-table-column>
          <el-table-column
            sortable
            :show-overflow-tooltip="true"
            min-width="160px"
            prop="forwardingUnitName"
            label="发货单位"
            align="center"
          ></el-table-column>
          <el-table-column
            sortable
            :show-overflow-tooltip="true"
            min-width="160px"
            prop="receivingUintName"
            label="收货单位"
            align="center"
          ></el-table-column>
          <el-table-column
            sortable
            :show-overflow-tooltip="true"
            min-width="80px"
            label="操作"
            align="center"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.valueFlag - 0 === 0"
                type="danger"
                size="mini"
                @click="entrustDrop(scope.row)"
                >作废</el-button
              >
              <el-button
                v-else
                type="primary"
                size="mini"
                @click="entrustRecover(scope.row)"
                >启用</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="common-foot-style">
        <el-pagination
          v-loading="dataLoading"
          @size-change="pageSizeChange"
          @current-change="pageCurrentChange"
          :current-page="page.pageNum"
          :page-sizes="[100, 500, 1000]"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.totalPage"
        >
        </el-pagination>
      </div>
    </el-card>
    <div id="qrcode2" v-show="false" ref="qrcode2">
      <div id="printContent">
        <div
          style="
            text-align: center;
            margin: 0 0 0px 0px;
            padding: 10px;
            width: 260px;
            height: 200px;
            display: flex;
            justify-content: center;
            align-items: center;
          "
          id="XQ"
        ></div>
        <div style="text-align: center; margin: 0 0 0px 0px; width: 260px">
          <strong style="font-size: 13px">临时委托号:{{ qrCode }}</strong
          ><br />
          <strong style="font-size: 13px"
            >物料名称:{{ currentRow.matterName }}</strong
          ><br />
          <strong style="font-size: 13px"
            >发货单位：{{ currentRow.forwardingUnitName }}</strong
          ><br />
          <strong style="font-size: 13px"
            >收货单位：{{ currentRow.receivingUintName }}</strong
          >
        </div>
      </div>
    </div>
    <el-dialog
      title="新增临时委托"
      :visible.sync="addDialogVisible"
      @close="closeAddDialog"
      :close-on-click-modal="false"
      width="450px"
      height="500px"
      class="entrust-wrap"
    >
      <el-form
        :model="editForm"
        ref="editForm"
        label-width="70px"
        size="mini"
        :rules="formRules"
      >
        <el-form-item label="物资名称">
          <el-select
            v-model="editForm.matterName"
            filterable
            clearable
            :filter-method="matFilter"
            @change="matChange"
          >
            <el-option
              v-for="item in matList"
              :key="item.matterNo"
              :value="item.matterName"
              :label="item.matterName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发货单位">
          <el-select
            v-model="editForm.forwardingUnitName"
            filterable
            clearable
            :filter-method="
              (val) => unitFilter(val, 'sdrList', 'forwardingUnitName')
            "
            @change="(val) => unitChange(val, 'sdrList', 'forwardingUnitNo')"
          >
            <el-option
              v-for="item in unitObj.sdrList"
              :key="item.customerSupplierNo"
              :value="item.customerSupplierName"
              :label="item.customerSupplierName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="收货单位">
          <el-select
            v-model="editForm.receivingUintName"
            filterable
            clearable
            :filter-method="
              (val) => unitFilter(val, 'rcvList', 'receivingUintName')
            "
            @change="(val) => unitChange(val, 'rcvList', 'receivingUintNo')"
          >
            <el-option
              v-for="item in unitObj.rcvList"
              :key="item.customerSupplierNo"
              :value="item.customerSupplierName"
              :label="item.customerSupplierName"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer" style="text-align: center">
        <el-button size="mini" type="default" @click="closeAddDialog"
          >取消</el-button
        >
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-add"
          @click="entrustCreate"
          >新增</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      @close="cloaserD"
      title="临时委托号生成"
      :visible.sync="dialogVisible"
      width="50%"
      height="500px"
    >
      <div id="qrcode3" ref="qrcode3">
        <div id="printContent2">
          <div
            style="
              text-align: center;
              margin: 0 0 0px 0px;
              padding: 10px;
              width: 100%;
              height: 400px;
              display: flex;
              justify-content: center;
              align-items: center;
            "
            id="XQ2"
          ></div>
          <div
            style="
              text-align: center;
              margin: 20px 0 20px 0px;
              width: 100%;
              color: black;
              font-size: 25px;
            "
          >
            <table style="width: 100%">
              <tr style="margin-bottom: 20px; height: 40px">
                <td style="width: 45%; text-align: right">临时委托号:</td>
                <td style="width: 55%; text-align: left">{{ qrCode }}</td>
              </tr>
              <tr style="margin-bottom: 20px; height: 40px">
                <td style="width: 45%; text-align: right">物料名称:</td>
                <td style="width: 55%; text-align: left">
                  {{ currentRow.matterName }}
                </td>
              </tr>
              <tr style="margin-bottom: 20px; height: 40px">
                <td style="width: 45%; text-align: right">发货单位:</td>
                <td style="width: 55%; text-align: left">
                  {{ currentRow.forwardingUnitName }}
                </td>
              </tr>
              <tr style="margin-bottom: 20px; height: 40px">
                <td style="width: 45%; text-align: right">收货单位:</td>
                <td style="width: 55%; text-align: left">
                  {{ currentRow.receivingUintName }}
                </td>
              </tr>
            </table>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { MessageBox } from 'element-ui';
import {
  cookieUserId,
  cookieUserName
} from '@/config/config.js';
import { getCookie } from '@/utils/util.js';

export default {
  data () {
    return {
      dataLoading: false,
      icoreFilterFlag: true,
      dialogVisible: false,
      page: {
        pageSize: 500,
        pageNum: 1,
        totalPage: 0
      },
      tableData: [],
      tableHeight: 0,
      matterRow: {},
      forwardingUnit: {},
      receivingUnit: {},
      multipleSelection: [],
      activeMenu: '',
      qrCode: '',
      searchForm: {
        matterName: '',
        forwardingUnitName: '',
        receivingUintName: '',
        valueFlag: '0'
      }, // 查询参数
      editForm: {
        matterName: '',
        matterMo: '',
        forwardingUnitName: '',
        forwardingUnitNo: '',
        receivingUintName: '',
        receivingUintNo: ''
      }, // 编辑数据对象
      editFormCache: {
        matterName: '',
        matterMo: '',
        forwardingUnitName: '',
        forwardingUnitNo: '',
        receivingUintName: '',
        receivingUintNo: ''
      }, // 编辑数据对象
      currentRow: {}, // 当前选中行
      addDialogVisible: false, // 新增临时委托窗口可见标志
      matList: [], // 物资名称
      unitObj: {
        sdrList: [],
        rcvList: []
      }, // 单位数据
      allMatList: [], // 所有物资数据
      allUnitList: [], // 所有单位数据
      formRules: {
        matterName: [{ required: true, message: '物资名称不能为空', trigger: 'blur' }],
        forwardingUnitName: [{ required: true, message: '发货单位不能为空', trigger: 'blur' }],
        receivingUintName: [{ required: true, message: '收货单位不能为空', trigger: 'blur' }]
      },
      userId: '',
      userName: '',
      qrRow: {},
      valueFlagList: [
        {
          id: '1',
          value: '已作废'
        },
        {
          id: '0',
          value: '有效'
        }
      ]
    }
  },
  created () {
    this.tableHeight = (window.innerHeight - 150) > 400 ? window.innerHeight - 150 : 400;
    this.activeMenu = window.top.localStorage.getItem('activeMenu')
  },
  mounted () {
    this.userName = getCookie(cookieUserName);
    this.userId = getCookie(cookieUserId);
    this.getDataList();
    this.matQuery();
    this.unitQuery();
  },
  methods: {
    // 临时委托查询
    getDataList (flag) {
      if (flag === 1) {
        this.page.pageNum = 1
      }
      this.dataLoading = true;
      let obj = {
        pageNum: this.page.pageNum,
        pageSize: this.page.pageSize,
        matterName: this.searchForm.matterName,
        forwardingUnitName: this.searchForm.forwardingUnitName,
        receivingUintName: this.searchForm.receivingUintName,
        valueFlag: this.searchForm.valueFlag
      }
      this.axios.post('pass/systemBase/v1/pretracktementrusts/doQuery', { param: { ...obj }, pageNum: this.page.pageNum, pageSize: this.page.pageSize }, { individualType: 'json' })
        .then(res => {
          this.dataLoading = false;
          this.tableData = [...res.data.list];
          this.page.totalPage = res.data.total;
        }).catch(e => {
          this.dataLoading = false;
        });
    },
    addDialog () {
      this.addDialogVisible = true
    },
    cloaserD () {
      this.dialogVisible = false
      // this.currentRow = {}
    },
    // 关闭弹窗
    closeAddDialog () {
      this.addDialogVisible = false;
      this.editForm = { ...this.editFormCache }
    },
    // 临时委托新增
    async entrustCreate () {
      this.$refs.editForm.validate(async valid => {
        if (!valid) return this.$message.error('请规范填写数据')
        let param = {
          ...this.editForm,
          createManNo: this.userId,
          createManName: this.userName
        }
        const data = await this.axios.post('pass/systemBase/v1/pretracktementrusts/add', param, { individualType: 'json' })
        if (data.status === 'succeed') {
          this.addDialogVisible = false
          this.editForm = { ...this.editFormCache }
          this.$message.success('新增成功')
        } else {
          this.$message.error(data.message)
        }
        this.getDataList(1)
      })
    },
    // 临时委托作废
    entrustDrop (row) {
      MessageBox.confirm('确认要作废选中的临时委托数据', '提示信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const data = await this.axios.put('pass/systemBase/v1/pretracktementrusts/update', { entrustNo: row.entrustNo, valueFlag: '1', updateManNo: this.userId, updateManName: this.userName }, { individualType: 'json' })
        console.log(data, '作废返回结果')
        if (data.status === 'succeed') {
          this.$message.success('作废成功');
          this.getDataList(1)
        }
      }).catch(() => {

      })
    },
    // 临时委托启用
    entrustRecover (row) {
      MessageBox.confirm('确认要启用选中的临时委托数据', '提示信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const data = await this.axios.put('pass/systemBase/v1/pretracktementrusts/update', { entrustNo: row.entrustNo, valueFlag: '0', updateManNo: this.userId, updateManName: this.userName }, { individualType: 'json' })
        console.log(data, '启用返回结果')
        if (data.status === 'succeed') {
          this.$message.success('启用成功');
          this.getDataList(1)
        }
      }).catch(() => {

      })
    },
    // 行点击
    rowChange (val) {
      this.currentRow = { ...val }
    },
    // 打印二维码
    printQRCode () {
      if (!this.currentRow.matterName) {
        return this.$message.error('请先点选一条数据')
      }
      let qrCode = this.currentRow.entrustNo;
      this.qrCode = qrCode;
      setTimeout(() => {
        document.getElementById("XQ").innerHTML = ""; //置空
        new QRCode(document.getElementById("XQ"), {
          text: qrCode,
          width: 180,
          height: 180,
          colorDark: "#000000",
          colorLight: "#ffffff",
        })
        setTimeout(async () => {
          await this.printPage('printContent');
        }, 500)
      }, 100)
    },
    // 生成二维码
    generateQRCode () {
      if (!this.currentRow.matterName) {
        return this.$message.error('请先点选一条数据')
      }
      let qrCode = this.currentRow.entrustNo;
      this.qrCode = qrCode;
      this.dialogVisible = true
      setTimeout(() => {
        document.getElementById("XQ2").innerHTML = ""; //置空
        let XQ2 = document.getElementById("XQ2")
        new QRCode(XQ2, {
          text: qrCode,
          width: 380,
          height: 380,
          colorDark: "#000000",
          colorLight: "#ffffff",
        })
      }, 100)
    },
    // 物资数据
    async matQuery () {
      this.axios.get('pass/systemBase/v1/meterbasematterinfos/noPage' + '?validFlag=1')
        .then(res => {
          this.allMatList = [...res.data]
          this.matList = [...this.allMatList].slice(0, 200)
        })
    },
    // 物资筛选
    matFilter (val) {
      this.editForm.matterName = val
      if (val) {
        let list = this.allMatList.filter(item => {
          if (item.matterName.indexOf(val) !== -1) {
            return true
          }
        })
        if (list.length === 0) {
          this.matList = [...list]
          this.editForm.matterName = val
        } else {
          this.matList = [...list].slice(0, 200)
        }
      } else {
        this.matList = [...this.allMatList]
      }
    },
    // 单位筛选
    unitFilter (val, name, valName) {
      this.editForm[valName] = val
      if (val) {
        let list = this.allUnitList.filter(item => {
          if (item.customerSupplierName.indexOf(val) !== -1) {
            return true
          }
        })
        this.unitObj[name] = [...list]
        if (list.length === 0) {
          this.editForm[valName] = val
        }
      } else {
        this.unitObj[name] = [...this.allUnitList].slice(0, 200)
      }
    },
    // 物资改变
    matChange (val) {
      let item = this.allMatList.find(item => item.matterName === val);
      if (item) {
        this.editForm.matterNo = item.matterNo
      }
    },
    // 单位改变
    unitChange (val, name, valName) {
      let item = this.allUnitList.find(item => item.customerSupplierName === val)
      if (item) {
        this.editForm[valName] = item.customerSupplierNo
      }
    },
    // 收发货单位
    async unitQuery () {
      const { data: res } = await this.axios.get('pass/systemBase/v1/meterbasecustomersuppliers/like/?pageNum=1&pageSize=100000&checkFlag=1&validFlag=1');
      this.allUnitList = [...res.list];
      this.unitObj.sdrList = [...res.list].slice(0, 200);
      this.unitObj.rcvList = [...res.list].slice(0, 200);
    },
    // 分页大小
    pageSizeChange (size) {
      this.page.pageSize = size;
      this.getDataList(1);
    },
    // 页码变化
    pageCurrentChange (index) {
      this.page.pageNum = index;
      this.getDataList();
    }
  }
}
</script>
<style scoped>
.el-table__body tr.current-row > td {
  background-color: #ff784a !important;
  color: #fff;
}
</style>
<style>
.entrust-wrap .el-dialog__header {
  padding: 10px !important;
  text-align: center !important;
}

.entrust-wrap .el-dialog__footer {
  text-align: center !important;
}

.entrust-wrap .el-select {
  width: 90%;
}
</style>