
<template>
    <div class="page">
        <LayoutTable :data='tableData' :config='tableConfig' notDel />
        <BomInfo :bomId.sync="bomId" @closeBomInfo="closeBomInfo" :bomInfoVisible.sync="bomInfoVisible"> </BomInfo>
      <!-- 导入弹框 -->
      <el-dialog title="批量导入" :visible.sync="dialogVisible" @close='dialogCancel' width="800px" :close-on-click-modal="false">
        <el-form :model="dialogForm" :rules="rules" ref="dialogForm">
          <el-row style="margin-left: 50px">
            <Field label="上传文件" prop="importFile" :span="24">
             <Upload v-model="dialogForm.importFile" prop="importFile" tip='上传文件' prePath="assetImport" />
            </Field>
          </el-row>
          <el-row style="margin-left: 50px">
            <Field label="提示" :span="24"><span class="el-tag--danger">上传文件格式请遵循此模板: </span> <a href="资产导入模板.xlsx">点击下载模板</a>，错误数据将不会被导入！</Field>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size='mini' @click="dialogCancel">取 消</el-button>
          <el-button size='mini'  type="primary" @click="submitUpload" >确 定</el-button>
        </div>
      </el-dialog>
    </div>
</template>

<script>
import table from "@/assets/mixins/table";
import qrcode from "@chenfengyuan/vue-qrcode";
import { post } from "@/assets/utils/ajax";
export default {
    mixins: [table],
    components: {
      qrcode
    },
    data() {
        return {
          bomInfoVisible: false,
          bomId: -1,
          dialogVisible : false,
          dialogForm: {
            importFile:''
          },
            config: {
              buttons: [
               /* {
                  label: "导入",
                  icon: "el-icon-upload2",
                  type : "default",
                  method : this.openUploadWindow,
                  loading : false,
                  isShow  : true,
                },*/
                {
                  label: "导出二维码",
                  icon: "el-icon-bottom",
                  type: "primary",
                  method: this.exportQRcode,
                  loading: false,
                  isShow: true
                },
              ],
                search: [
                    {
                        name: "assetNum",
                        type: "text",
                        label: "资产码",
                        fuzzy: true
                    },
                  {
                    name: "deviceNum",
                    type: "text",
                    label: "业务码",
                    fuzzy: true
                  },
                  {
                    name: "flowStatus",
                    type: "select",
                    label: "业务流转状态",
                  },
                ],
                columns: [

                  {
                    type: "selection",
                    width: 40
                  },
                    {
                        prop: "assetNum",
                        label: "资产码",
                        sortable:true,
                      formatter: row => {
                        return (
                            <span>
                                    <a
                                        size="mini"
                                        style="color: DodgerBlue;"
                                        onClick={() => this.toView(row)}
                                    >
                                        {row.assetNum}
                                    </a>
                                    <span
                                        title="资产二维码"
                                        class="el-icon-menu"
                                        style="float:right;cursor: pointer;"
                                        onClick={() => {
                                          this.toShowQR(row);
                                        }}
                                    ></span>
                                </span>
                        );
                      }
                    },

                    {
                        prop: "deviceNum",
                        label: "业务码",

                    },
                  {
                    prop: "bomId",
                    label: "Bom版本",
                    width: 280,
                    formatter: this.formatter,
                  },

                    {
                        prop: "materiaId",
                        label: "所属物料",
                        width: 220,
                        formatter: this.formatter,
                    },


                    {
                        prop: "producerId",
                        label: "生产厂家",
                        formatter: this.formatter,
                    },

                    {
                        prop: "produceDate",
                        label: "生产日期",
                        width: 140,
                        formatter: this.formatterDateOnly,
                    },

                    {
                        prop: "produceCost",
                        label: "生产成本(元)",
                        width: 90,
                        formatter: this.formatterMoney,
                    },

                    {
                        prop: "flowStatus",
                        label: "流转状态",
                        width: 100,
                        formatter: this.formatter,
                    },

                    {
                        prop: "enabled",
                        label: "是否启用",
                        width: 70,
                        formatter: this.formatter,
                    },

                    {
                        label: "操作",
                        width: 240,
                        formatter: (row) => {
                            return (
                                <div>
                                  <table-buttons row={row} onEdit={this.toEdit} noDel onView={this.toView} />
                                  {row.enabled == 0 ? (
                                      <Confirm onConfirm={() => { this.operEnabled(row.id, 1); }}  message="是否启用该资产？"><span>&nbsp;&nbsp;</span>
                                        <el-button size="mini" type="success" icon="el-icon-check" circle title="启用" ></el-button>{" "}
                                      </Confirm>) : ("")}
                                  {row.enabled == 1 ? (
                                      <Confirm onConfirm={() => { this.operEnabled(row.id, 0); }}  message="是否停用该资产？"><span>&nbsp;&nbsp;</span>
                                        <el-button size="mini" type="warning"  icon="el-icon-video-pause" circle title="停用" ></el-button>{" "}
                                      </Confirm>) : ("")}
                                    <el-button size="mini" type="info"  icon="el-icon-notebook-2"  onClick={() => {this.toEventLogPage(row);}} circle title="查看日志" ></el-button>
                                    <el-button size="mini" type="info"  icon="el-icon-notebook-1"  onClick={() => {this.showBomInfo(row);}} circle title="查看bom信息" ></el-button>

                                </div>


                            );
                        },
                    },
                ],
            },
        };
    },
    methods: {
      beforeFetchData(data) {
        const searchForm = {};
        Object.keys(data).forEach(key => {
          var reqKey = key;
          if (data[key] !== "") {
            searchForm[key] = undefined;
            searchForm[reqKey] = data[key];
          }
        });
        data = Object.assign({}, data, searchForm);

        if(data['query.orderColList[0]'] && data['query.orderColList[0]'].colName==undefined){
          data['query.orderColList[0]']={};
        }
        if(undefined != data['query.orderColList[0]']){
          searchForm['query.orderColList[0]']= data['query.orderColList[0]'];
          this.$route.query["query.orderColList[0]"] = data['query.orderColList[0]'];
        }

        return data;
      },
      // 表格排序
      handleSortChange(row) {
        const { prop, order } = row;
        let orderCol = {
          colName: prop,
          sortKind: order === "ascending" ? "asc" : "desc"
        };
        this.$set(
            this.query,
            "query.orderColList[0]",
            prop ? orderCol : {}
        );
        this.getData();
      },
      showBomInfo(row){
        this.bomId = row.bomId;
        this.bomInfoVisible = true;
      },
      closeBomInfo(type){
        this.bomInfoVisible = false;
      },
      openUploadWindow() {
        this.dialogForm.importFile ='';
        this.dialogVisible = true;
      },
      dialogCancel(){
        this.dialogVisible = false;
      },
      async submitUpload(){
        if(!this.dialogForm.importFile){
          this.$message.warning('请上传');
        }
        try {
          await this.$post("/asset/saveImport",
              {'importFile': this.dialogForm.importFile})
              .then(res => {
                let result = res.data.importResult;
                if(result && result.errorNumber ==0){

                  this.$message("导入成功，成功条数：" + result.successNumber +" 条")
                }else if( result.errorNumber != 0){
                    let html = "<div>"

                        +  "<p>成功条数：<span style='color:green;'>" + result.successNumber +"</span> 条</p><br>"
                        +  "<p>失败条数：<span style='color:red;'>" + result.errorNumber +" </span>条</p><br>"
                        +  "<p><p>失败详情：</p><p>" ;
                        for(var i = 0; i < result.errRows.length; i++){
                          html = html+ "<div style='padding-top:10px'>" + result.errRows[i] + ";</div>";
                        }
                    html = html +" </p></p>"
                        +"</div>";
                  this.$message({
                    showClose: true,
                    dangerouslyUseHTMLString: true,
                    message: html,
                    duration:10000,
                  });
                }

                this.getData();
                this.dialogVisible = false;

              })
              .catch(error => {
                console.log(11111);
                console.log(error);
                this.$message({
                  message: error.message,
                  type: 'error',
                  duration: 6000
                });
              });
        }catch(error){
          this.$message.warning('导入失败');
        }
      },

      // 状态操作
      async operEnabled(id, enabled) {
        const entity = {
          id: id,
          enabled: enabled,
        };
        this.$post("/asset/operEnabled", { entity: entity })
            .then(({ data, msg }) => {
              msg && this.$message.success(msg);
              this.getData();
            })
            .catch((error) => {
              this.$message.error(error.message);
            });
      },

      //跳转日志页面
      toEventLogPage(row){
        this.$router.push({
          path: "/asset/flow/eventlog/list"  ,
          query: { "query.assetNum": '%' + row.assetNum + '%' },
        })
      },

      toShowQR(val) {
        let qrcode =  val.assetNum;
        const h = this.$createElement;
        this.$msgbox({
          title: "资产二维码",
          message:
              h("p", null, [
                h(
                    "qrcode",
                    {
                      attrs: {
                        name: qrcode,
                        class: "qrcode",
                        options: { width: "200" },
                        value: qrcode
                      }
                    },
                    qrcode
                ),
                h("p", null, qrcode)
              ]),
          //           showConfirmButton: false,
          showCancelButton: true,
          confirmButtonText: "下载",
          cancelButtonText: "关闭",
          center: true
        })
            .then(action => {
              let canvas = document.querySelector(".qrcode");
              var a = document.createElement("a");
              a.href = canvas.toDataURL();
              a.download = qrcode;
              a.click();
            })
            .catch(() => {});
      },
      /**
       * 导出二维码
       * @returns {Promise}
       */
      exportQRcode() {
        if (this.selection && this.selection.length == 0) {
          return this.$message({
            message: "请选择需要导出二维码的资产",
            type: "warning"
          });
        }
        this.$confirm("导出二维码需要较长时间, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
            .then(async () => {
              return new Promise(async (resolve, reject) => {
                const option = Object.assign(
                    {},
                    {},
                    {
                      responseType: "blob"
                    }
                );

                this.config.buttons[1].loading = true;
                try {
                  let url = "/asset/exportQRcode";
                  this.query["query.idList"] = this.selection;
                  const data = await post(url, this.query, option);
                  console.log(data);
                  if (data.type == "application/octet-stream") {
                    let downloadUrl = window.URL.createObjectURL(
                        new Blob([data])
                    );
                    let link = document.createElement("a");
                    link.style.display = "none";
                    link.href = downloadUrl;
                    link.setAttribute(
                        "download",
                        `${url
                            .substr(1)
                            .replace(
                                /\//g,
                                "_"
                            )}_${new Date().getTime()}.zip`
                    );
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    resolve();
                  } else {
                    data.text().then(text => {
                      this.$message.warning(text);
                    });
                  }
                } catch (error) {
                  reject(error);
                }
                this.query["query.idList"] = [];
                this.config.buttons[1].loading = false;
              });
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消"
              });
            });
      },
    }
};
</script>
