<template>
  <div class="">
    <div class="">
      <div class="tableWrap">
        <el-table
          :header-cell-style="{ background: '#EDEEF0', color: '#444' }"
          :data="tableList"

        >
        <!--   @selection-change="handleSelectionChange" -->
          <!-- <el-table-column type="selection" width="55"> </el-table-column> -->
          <el-table-column label="商品编号" prop="sn" align="center">
          </el-table-column>
          <el-table-column label="商品名称" align="center" prop="name">
          </el-table-column>
          <el-table-column label="商品类型" align="center" prop="type">
            <template slot-scope="scope">
              <div>
                {{ scope.row.type | shopType }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="具体型号" align="center" prop="specification">
          </el-table-column>
          <el-table-column label="数量统计" align="center" prop="sellCount">
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="btnWrap" style="margin-top: 20px">
      <el-button
        type="primary"
        v-if="tableList.length > 0"
        v-permission="'order/musicalListExport'"
        @click="musicalListExport"
        >订货清单导出</el-button
      >
      <el-button
        type="primary"
        v-if="tableList.length > 0"
        v-permission="'order/musicalListDetailExport'"
        @click="musicalListDetailExport"
        >分发清单导出</el-button
      >
      <!--  v-if="
          musicalStatus &&
          $helpers.permission('musicGroup/takeEffectOfinstrumentInsurance')
        " -->
      <el-button
        type="primary"
        @click="onDelivery"

        >确认发货</el-button
      >
      <!-- <el-button
        type="warning okBtn"
        v-if="team_status == 'PREPARE' && !hasVerifyMusicalList"
        v-permission="'order/verifyMusicalList'"
        @click="okDetailList"
        >乐器清单确认</el-button
      > -->
      <!-- <div class="okBtn" v-permission="'order/verifyMusicalList'"
           @click="okDetailList">确认</div> -->
    </div>
    <el-dialog :visible.sync="addrVisiable" title="确认清单" width="500px">
      <deliverGoods v-if="addrVisiable" :form="activeChiose" ref='deliverGoods' @close='()=>{addrVisiable = false}' @getList='getList'/>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addrVisiable = false">取 消</el-button>
        <el-button type="primary" @click="onsubmitDelivery"
          >确 定</el-button
        >
      </div>
    </el-dialog>

  </div>
</template>
<script>
import { getTeamDetailList, getTeamBaseInfo } from "@/api/buildTeam";
import { getTeamList } from "@/api/teamServer";
import {
  verifyMusicalList,
  takeEffectOfinstrumentInsurance,
} from "@/api/orderManager";
import deliverGoods from './modals/deliverGoods.vue'
import axios from "axios";
import qs from "qs";
import { getToken, getTenantId } from "@/utils/auth";
import load from "@/utils/loading";
export default {
  data() {
    return {
      teamid: "",
      tableList: [],
      Fsearch: null,
      Frules: null,
      team_status: "",
      musicalInstrumentsProvideStatus: 0, // 是否确认发货  1已发货
      hasVerifyMusicalList: true,
      activeChiose:[],
      addrVisiable:false
    };
  },
  components:{deliverGoods},
  mounted() {
    this.init();
  },
  activated() {
    this.init();
  },
  computed: {
    musicalStatus() {
      const template = ["PREPARE", "PROGRESS"];
      const teamStatus = this.$route.query.team_status;
      const status = template.includes(teamStatus);
      console.log(this.musicalInstrumentsProvideStatus, status);
      return !this.musicalInstrumentsProvideStatus && status ? true : false;
    },
  },
  methods: {
    init() {
      this.team_status = this.$route.query.team_status;
      this.teamid = this.$route.query.id;
      if (this.teamid) {
        // getTeamList({ musicGroupId: this.teamid }).then(res=>{
        //   if(res.code == 200){
        //     this.hasVerifyMusicalList = res?.data?.rows[0]?.hasVerifyMusicalList
        //   }
        // })
          this.getList()
        this.getMusicInfo();
      }
    },
    getList(){
      this.addrVisiable=false;
      getTeamDetailList({ musicGroupId: this.teamid,deliveryStatus:'0' }).then((res) => {
          if (res.code == 200) {
            this.tableList = res.data ? res.data : [];
          }
        });
    },
    async getMusicInfo() {
      await getTeamBaseInfo({ musicGroupId: this.teamid  }).then((res) => {
        if (res.code == 200) {
          this.musicalInstrumentsProvideStatus =
            res.data?.musicGroup?.musicalInstrumentsProvideStatus;
          this.hasVerifyMusicalList =
            res.data?.musicGroup?.hasVerifyMusicalList;
        }
      });
    },
    handleSelectionChange (val) {
      this.activeChiose = val
    },
    onCancel() {
      this.$store.dispatch("delVisitedViews", this.$route);
      this.$router.push({ path: "/teamList" });
    },
    onDelivery() {
      // console.log('自动发货')
      this.addrVisiable = true;
      // return
      // this.$confirm("是否确认发货", "提示", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   type: "warning",
      // }).then(async () => {
      //   try {
      //     await takeEffectOfinstrumentInsurance({ musicGroupId: this.teamid });
      //     this.$message.success("确定发货成功");
      //     this.getMusicInfo();
      //   } catch {
      //     //
      //   }
      // });
    },
    onsubmitDelivery(){
      this.$refs.deliverGoods.submit()
      console.log('确认发货发货')
    },
    okDetailList() {
      this.$confirm(`是否确认发放清单?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          verifyMusicalList({ musicGroupId: this.teamid }).then((res) => {
            if (res.code == 200) {
              this.$store.dispatch("delVisitedViews", this.$route);
              this.$router.push({
                path: "/teamList",
                query: { search: this.Fsearch, rules: this.Frules },
              });
            }
          });
        })
        .catch(() => {});
    },
    musicalListExport() {
      // 报表导出
      let url = "/api-web/order/musicalListExport";
      let data = {
        musicGroupId: this.$route.query.id,
        deliveryStatus:'0'
      };
      const options = {
        method: "POST",
        headers: {
          Authorization: getToken(),
          tenantId: getTenantId(),
        },
        data: qs.stringify(data),
        url,
        responseType: "blob",
      };
      this.$confirm("您确定导出订货清单", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          load.startLoading();
          axios(options)
            .then((res) => {
              let blob = new Blob([res.data], {
                // type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
                type: "application/vnd.ms-excel;charset=utf-8",
                //word文档为application/msword,pdf文档为application/pdf,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8
              });
              let text = new Response(blob).text();
              text.then((res) => {
                // 判断是否报错
                if (res.indexOf("code") != -1) {
                  let json = JSON.parse(res);
                  if (json.code == 403) {
                    this.$message.error(`登录过期，请重新登录！`);
                    setTimeout(() => {
                      this.$store.dispatch("user/resetToken").then(() => {
                        location.reload();
                      });
                    }, 1000);
                    return;
                  }
                  this.$message.error(json.msg);
                } else {
                  let objectUrl = URL.createObjectURL(blob);
                  let link = document.createElement("a");
                  let nowTime = new Date();
                  let ymd =
                    nowTime.getFullYear() +
                    "" +
                    (nowTime.getMonth() + 1) +
                    "" +
                    nowTime.getDate() +
                    "" +
                    nowTime.getHours() +
                    "" +
                    nowTime.getMinutes();
                  let fname = this.$route.query.id + "-" + ymd + "订货清单.xls"; //下载文件的名字
                  link.href = objectUrl;
                  link.setAttribute("download", fname);
                  document.body.appendChild(link);
                  link.click();
                }
              });
              load.endLoading();
            })
            .catch((error) => {
              this.$message.error("导出数据失败，请联系管理员");
              load.endLoading();
            });
        })
        .catch(() => {});
    },
    musicalListDetailExport() {
      // 报表导出
      let url = "/api-web/order/musicalListDetailExport";
      let data = {
        musicGroupId: this.$route.query.id,
        deliveryStatus:'0'
      };
      const options = {
        method: "POST",
        headers: {
          Authorization: getToken(),
          tenantId: getTenantId(),
        },
        data: qs.stringify(data),
        url,
        responseType: "blob",
      };
      this.$confirm("您确定导出分发清单", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          load.startLoading();
          axios(options)
            .then((res) => {
              let blob = new Blob([res.data], {
                // type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
                type: "application/vnd.ms-excel;charset=utf-8",
                //word文档为application/msword,pdf文档为application/pdf,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8
              });
              let text = new Response(blob).text();
              text.then((res) => {
                // 判断是否报错
                if (res.indexOf("code") != -1) {
                  let json = JSON.parse(res);
                  if (json.code == 403) {
                    this.$message.error(`登录过期，请重新登录！`);
                    setTimeout(() => {
                      this.$store.dispatch("user/resetToken").then(() => {
                        location.reload();
                      });
                    }, 1000);
                    return;
                  }
                  this.$message.error(json.msg);
                } else {
                  let objectUrl = URL.createObjectURL(blob);
                  let link = document.createElement("a");
                  let nowTime = new Date();
                  let ymd =
                    nowTime.getFullYear() +
                    "" +
                    (nowTime.getMonth() + 1) +
                    "" +
                    nowTime.getDate() +
                    "" +
                    nowTime.getHours() +
                    "" +
                    nowTime.getMinutes();
                  let fname = this.$route.query.id + "-" + ymd + "分发清单.xls"; //下载文件的名字
                  link.href = objectUrl;
                  link.setAttribute("download", fname);
                  document.body.appendChild(link);
                  link.click();
                }
              });
              load.endLoading();
            })
            .catch((error) => {
              this.$message.error("导出数据失败，请联系管理员");
              load.endLoading();
            });
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss" scoped>
</style>
