<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="资产名称：" prop="name">
        <el-input
          v-model.trim="queryParams.name"
          placeholder="请输入资产名称"
          clearable
          size="small"
          style="width: 160px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="存放地点：" prop="address">
        <el-input
          v-model.trim="queryParams.address"
          placeholder="请输入存放地点"
          clearable
          size="small"
          style="width: 160px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:admin:add']"
        >新增</el-button>
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['system:admin:export']"
        >导出</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="adminList" height="calc(100vh - 28vh)">
    <el-table-column label="资产编号" align="center" prop="facilityNo"  show-overflow-tooltip />
    <el-table-column label="资产名称" align="center" prop="facilityName"  show-overflow-tooltip />
    <el-table-column label="资产类型" align="center" prop="facilityType"  show-overflow-tooltip >
      <template slot-scope="scope">
        <span>{{ scope.row.facilityType == 1 ? '办公用品': scope.row.facilityType == 2 ? '办公设备' :
          scope.row.facilityType == 3 ? '计算机及外围设备': scope.row.facilityType == 4 ? '数码及影音设备' :
          scope.row.facilityType == 5 ? '运输工具': scope.row.facilityType == 6 ? '自动化办公设备' :
          scope.row.facilityType == 7 ? '其它': "" }}</span>
      </template>
    </el-table-column>
    <el-table-column label="负责人" align="center" prop="man"  show-overflow-tooltip />
    <el-table-column label="购入方式" align="center" prop="purchase"  show-overflow-tooltip />
    <el-table-column label="存放地点" align="center" prop="addrs"  show-overflow-tooltip />
    <el-table-column label="购入日期" align="center" prop="buyTime"  show-overflow-tooltip />
    <el-table-column label="购买编号" align="center" prop="buyNo"  show-overflow-tooltip />
    <el-table-column label="发票号" align="center" prop="invoice"  show-overflow-tooltip />
    <el-table-column label="资产二维码" align="center" prop="qrurl" show-overflow-tooltip >
      <template slot-scope="scope">
  <!-- 　　　　<img :src="'http://172.16.120.104:8084/archive/' + scope.row.qrurl" width="40" height="40" class="head_pic"/> -->
          <el-image
            v-if="scope.row.qrurl"
            style="width: 24px; height: 24px"
            :preview-src-list="['https://smartpark.caih.com/dmapi/archive/' + scope.row.qrurl]"
            :src="'https://smartpark.caih.com/dmapi/archive/' + scope.row.qrurl">
          </el-image>
  　　</template>
    </el-table-column>
    <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="handleUpdate(scope.row)"
            v-hasPermi="['system:admin:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:admin:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 修改、新增对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px"  append-to-body :before-close="cancel" :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" >
        <el-row>
          <el-col :span="12">
            <el-form-item label="资产编号" prop="facilityNo">
              <el-input v-model.trim="form.facilityNo" placeholder="请填写资产编号" @input="onInput()" maxlength="10" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资产名称" prop="facilityName">
              <el-input v-model.trim="form.facilityName" placeholder="请填写资产名称" @input="onInput()" maxlength="10" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="购买时间" prop="buyTime">
              <el-date-picker
                v-model="form.buyTime"
                type="date"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="单位名称：" prop="company">
                <el-select
                  v-model="form.company"
                  placeholder="请选择单位名称"
                  clearable
                  size="small"
                >
                  <el-option
                    v-for="dict in companyList"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  />
                </el-select>
              </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="man">
              <el-input v-model.trim="form.man" placeholder="请填写负责人" @input="onInput()" maxlength="10" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="购入方式" prop="purchase">
              <el-select v-model="form.purchase"  placeholder="购入方式">
                <el-option
                  v-for="item in purchaseList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="型号" prop="facilityModel">
              <el-input v-model.trim="form.facilityModel" placeholder="请填写型号" @input="onInput()" maxlength="10" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="计量单位" prop="unit">
              <el-input v-model.trim="form.unit" placeholder="请填写计量单位" @input="onInput()" maxlength="4" show-word-limit/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数量" prop="number">
              <el-input type="text" onkeyup="this.value=this.value.replace(/^\.+|[^\d\.]/g,'')" onblur="if(this.value ==0||!/^\d+(\.\d{1,2})?$/.test(this.value))this.value=''"
              v-model.trim="form.number" placeholder="请填写数量" @input="onInput()" maxlength="5" show-word-limit/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="单价" prop="price">
              <el-input type="text"  onkeyup="this.value=this.value.replace(/^\.+|[^\d\.]/g,'')"
              onblur="if(this.value ==0||!/^\d+(\.\d{1,2})?$/.test(this.value))this.value=''"
              v-model.trim="form.price" placeholder="请填写单价" @input="onInput()"  maxlength="9" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="存放地点" prop="addrs">
              <el-input type="textarea" v-model.trim="form.addrs" placeholder="请填写存放地址" @input="onInput()" rows="3" maxlength="20" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplier">
              <el-input v-model.trim="form.supplier" placeholder="请填写供应商" @input="onInput()" maxlength="12" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购编号" prop="buyNo">
              <el-input v-model.trim="form.buyNo" placeholder="请填写采购编号" @input="onInput()" maxlength="15" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="发票编号" prop="invoice">
              <el-input v-model.trim="form.invoice" placeholder="请填写发票编号" @input="onInput()" maxlength="15" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资产用途" prop="purpose">
              <el-input v-model.trim="form.purpose" placeholder="请填写资产用途" @input="onInput()" maxlength="15" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="维修周期" prop="warrantyPeriod">
              <el-input v-model.trim="form.warrantyPeriod" placeholder="请填写维修周期" @input="onInput()" maxlength="4" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维修天数" prop="warranty">
              <el-input type="text" onkeyup="this.value=this.value.replace(/^\.+|[^\d\.]/g,'')"
              onblur="if(this.value ==0||!/^\d+(\.\d{1,2})?$/.test(this.value))this.value=''"
              v-model.trim="form.warranty" placeholder="请填写维修天数" @input="onInput()" maxlength="4" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="已使用年限" prop="usedData">
              <el-input type="text" onkeyup="this.value=this.value.replace(/^\.+|[^\d\.]/g,'')"
              onblur="if(this.value ==0||!/^\d+(\.\d{1,2})?$/.test(this.value))this.value=''" maxlength="2" show-word-limit
              v-model.trim="form.usedData" placeholder="请填写使用年限" @input="onInput()"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资产类别" prop="facilityType">
              <el-select v-model="form.facilityType"  placeholder="请选择类别">
                <el-option
                  v-for="item in facilityTypeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />
     <!-- 导出-->
    <a href="" download="" id="xz" style="position: absolute;z-index: -1;opacity: 0;"></a>
    <div class="qrcode" ref="qrCodeUrl" style="position: absolute;z-index: -1;opacity: 0;"></div>
  </div>
</template>
<script>
import { addPropertyMange, delPropertyMange, updatePropertyMange, getPropertyMange, getPropertyMangeType, exportPropertyMange } from "@/api/business/propertyMange";
import { listChannel } from "@/api/system/product";
import { timestampToTime } from "@/assets/js/dataFormate.js";
import { BASEPATH } from "@/assets/js/common.js";
import QRCode from 'qrcodejs2'
import { fileUpload } from "@/api/business/uploadfile.js";
export default {
  name: "admin",
  data() {
    return {
      base64:undefined,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 参数表格数据
      adminList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        name: undefined,
        address: undefined,
      },
      // 表单参数
      form: {

      },
      // // 日期范围
      // dateRange: [],
      //购入方式列表 =>表单
      purchaseList:[
        {id:"自购",name:"自购"},
        {id:"其他",name:"其他"},
      ],

      //单位列表 =>表单
      companyList:[

      ],
      //类别列表 =>表单
      facilityTypeList:[
        {id:1,name:"办公用品"},
        {id:2,name:"办公设备"},
        {id:3,name:"计算机及外围设备"},
        {id:4,name:"数码及影音设备"},
        {id:5,name:"运输工具"},
        {id:6,name:"自动化办公设备"},
        {id:7,name:"其它"},
      ],

      // 表单校验
      rules: {
        facilityNo:[
          { required: true, message: "资产编号不能为空", trigger: "blur" }
        ],
        facilityName: [
          { required: true, message: "资产名称不能为空", trigger: "blur" }
        ],

        facilityType: [
          { required: true, message: "类别不能为空", trigger: ["blur",'change'] }
        ],
        buyTime: [
          { required: true, message: "购买时间不能为空", trigger: "blur" }
        ],
        company: [
          { required: true, message: "使用单位不能为空", trigger: ["blur",'change']}
        ],
        man: [
          { required: true, message: "负责人不能为空", trigger: "blur" }
        ],
        purchase: [
          { required: true, message: "购入方式不能为空", trigger: ["blur",'change'] }
        ],
        addrs: [
          { required: true, message: "存放地点不能为空", trigger: "blur" }
        ],
        supplier: [
          { required: true, message: "供应商不能为空", trigger: "blur" }
        ],
        buyNo: [
          { required: true, message: "采购编号不能为空", trigger: "blur" }
        ],
        invoice: [
          { required: true, message: "发票编号不能为空", trigger: "blur" }
        ],
        purpose: [
          { required: true, message: "资产用途不能为空", trigger: "blur" }
        ],
        warrantyPeriod: [
          { required: true, message: "维修周期不能为空", trigger: "blur" }
        ],
        warranty: [
          { required: true, message: "维修天数不能为空", trigger: "blur" }
        ],
        usedData: [
          { required: true, message: "已使用年限不能为空", trigger: "blur" }
        ],

      }
    };
  },
  created() {
    this.getList();//初始化table
    this.company();//初始化单位选项
  },
  methods: {
    creatQrCode(text) {//生成二维码
      var qrcode = new QRCode(this.$refs.qrCodeUrl, {
          text: "资产编号：" + text,
          width: 500,
          height: 500,
          colorDark: '#000000',
          colorLight: '#ffffff',
          correctLevel: QRCode.CorrectLevel.H
      })
      setTimeout(()=>{
        this.base64 = window.atob(document.getElementsByClassName("qrcode")[0].getElementsByTagName("img")[0].src.split(',')[1]);
        this.handleChange(this.base64)
      },100)

    },
    handleChange(bytes){ //二维码上传
      var array = [];
      for(var i = 0; i < bytes.length; i++){
          array.push(bytes.charCodeAt(i));
      }
      var blob = new Blob([new Uint8Array(array)], {type: 'image/jpeg'});
      var formData = new FormData();
      formData.append('file',blob, Date.now() + '.jpg');
      formData.append('multipart',blob, Date.now() + '.jpg');
      fileUpload(formData).then(response => {
        this.form.qrurl = response.data
        this.addData()
      });
    },
    //强制el-input刷新
    onInput(){
        this.$forceUpdate();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.queryParams = {
        name:undefined,
        address:undefined,
        current:1,
        size:20
      }
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 表单重置
    reset() {
      this.form = {
        ids: undefined,
        name: undefined,
        topChannelName: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    /** 查询参数列表 */
    getList() {
      this.loading = true;
      //@ts-nocheckgetPropertyMange(this.addDateRange(this.queryParams,this.dateRange)).then(response => {
      getPropertyMange(this.queryParams).then(response => {
        this.adminList = response.data.records;
        console.log(this.adminList)
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 公司下拉列表 */
    company(){
      listChannel(this.queryParams).then(response => {
        if(response.data.records.length>0){
          this.companyList = response.data.records.map(val =>{
            return {
              dictValue:val.ownerId,
              dictLabel:val.ownerName,
              address:val.ownerAddress,
            }
          })
        }
      });
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.title = "修改";
      this.form = JSON.parse(JSON.stringify(row))
      this.open = true;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增";
    },
    /** 提交按钮 */
    submitForm(row) {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.loading = true
          this.form.buyTime = timestampToTime(this.form.buyTime)
          if (this.form.id != undefined) {
            updatePropertyMange(this.form).then(response => {
              this.loading = false,
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).catch(()=>{
              this.loading = false,
              this.open = false;
            })
          } else {
            this.creatQrCode(this.form.facilityNo)
          }
        }
      });
    },
    /** 新增数据 */
    addData(){
      addPropertyMange(this.form).then(response => {
        this.loading = false,
        this.msgSuccess("新增成功");
        this.open = false;
        this.getList();
      }).catch(()=>{
        this.loading = false,
        this.open = false
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delPropertyMange(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },

    /** 导出按钮操作 */
    handleExport() {
      let queryParams = {...this.queryParams};
      delete queryParams.current
      delete queryParams.size
      this.exportLoading = true;
      exportPropertyMange(queryParams,this.dateRange).then(response =>{
        this.exportLoading = false;
        document.getElementById("xz").href = BASEPATH() + response.data
        document.getElementById("xz").download = response.data
        document.getElementById("xz").click()
      })
    }
  }
};
</script>
