<!-- 经销商授权信息管理--列表 -->
<template>
  <el-card class="dealerAuthorization" v-loading="loading" :body-style="{ padding: 0 }">

    <authprivAdd ref="addDialogRef" @close="handleRefresh"></authprivAdd>
    <authprivSee ref="seeDialogRef"></authprivSee>

    <!-- 检索区 -->
    <el-form :inline="true" size="mini" label-position="right" label-width="100px" :model="searchParams"
      style="padding: 10px 0 0 0">

      <el-form-item v-for="column in searchColumns " :label="column.title" :key="column.key">

        <el-input v-if="column.type == 'Input'" v-model="searchParams[column.key]" clearable></el-input>

        <el-select v-else-if="column.type == 'Select'" v-model="searchParams[column.key]" clearable>
          <el-option v-for="op in column.options" :label="op.label" :value="op.value"></el-option>
        </el-select>

        <el-date-picker v-else-if="column.type == 'DateRange'" v-model="searchParams[column.key]" clearable
          type="daterange" format="yyyy-MM-dd " value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>

        <el-date-picker v-else-if="column.type == 'Date'" v-model="searchParams[column.key]" format="yyyy-MM-dd "
          clearable value-format="yyyy-MM-dd" type="date" :placeholder="column.config.placeholder" style="width: 192px;">
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handelSearch"
          v-hasPermi="['pu:authorization:list']">查询</el-button>
        <el-button icon="el-icon-refresh" @click="handelResetSearch">重置</el-button>
      </el-form-item>

    </el-form>

    <!-- 操作区 -->
    <el-row :gutter="24" style="padding: 0 10px">
      <el-col :span="24" style="text-align: right">
        <el-button size="mini" type="primary" @click="handleOpenAddDialog"
          v-hasPermi="['pu:authorization:add']">新增</el-button>
        <!-- <el-button size="mini" @click="handleSubmit">提交</el-button> -->
        <!-- <el-button size="mini" @click="handleDownload">下载授权书</el-button> -->
      </el-col>
    </el-row>

    <!-- 数据展示 -->
    <el-table class="da-table" @row-dblclick="handleOpenSeeDialog" @select="handleSelect" :data="tableData"
      highlight-current-row max-height="500">
      <el-table-column type="selection" width="45"></el-table-column>
      <el-table-column type="index" width="55" label="序号"></el-table-column>
      <el-table-column v-for="column in tableColumns" :label="column.title" v-if="column.show"
        :width="column.width || 120" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ column.key == 'status' ? judgeStatus(scope.row[column.key]) : scope.row[column.key] }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="120">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="handleOpenAddDialog(scope.row)"
            v-if="scope.row.status == '0' || scope.row.status == '3'"
            v-hasPermi="['pu:authorization:edit']">编辑</el-button>
          <el-button type="text" size="mini" @click="handleDelDialog(scope.row)"
            v-if="scope.row.status == '0' || scope.row.status == '3'"
            v-hasPermi="['pu:authorization:remove']">删除</el-button>
          <!-- <el-button @click="handleOpenSeeDialog(scope.row)" type="text" size="small">查看</el-button> -->
          <el-button type="text" size="mini" v-if="scope.row.status == '0' || scope.row.status == '3'"
            @click="handleSubmit(scope.row)">提交</el-button>
          <el-button type="text" size="mini" v-if="scope.row.status == '2'"
            @click="handleDownload(scope.row)">下载授权书</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :total="page.total"
      :page-sizes="pageSizes" :page-size="page.pageSize" :current-page="page.pageNum" hide-on-single-page
      :layout="layout">
    </el-pagination>

  </el-card>
</template>

<script>
import dealerApi from '@/api/marketing/dealer-authorization';
import { TableColumns, SearchColumns } from './column';
import { initParams } from '../utils/init';

export default {

  name: 'dealerAuthorization',
  components: {
    authprivAdd: () => import('./authprivAdd.vue'),
    authprivSee: () => import('./authprivSee.vue'),
  },

  data() {

    return {
      loading: false,
      searchColumns: SearchColumns,
      searchParams: {
        ...initParams(SearchColumns),
      },
      tableColumns: TableColumns,
      tableData: [],
      checkedList: [],
      page: {
        pageNum: 1,
        pageSize: 25,
        total: 0
      },
      pageSizes: [10, 20, 50, 100],
      layout: 'total, prev, pager, next, sizes, jumper',
    }
  },
  methods: {
    // 查询---列表查询
    async handelSearch() {
      this.loading = true;
      console.log(this.searchParams, '查询');
      // let isTime = this.searchParams.time && this.searchParams.time != '' && this.searchParams.time.length;
      let { pageNum, pageSize } = this.page;
      let params = {
        ...this.searchParams,
        // startTime: isTime ? this.searchParams.time[0] : '',
        // endTime: isTime ? this.searchParams.time[1] : '',
        pageNum: pageNum,
        pageSize: pageSize,
      }
      delete params['time']
      console.log(params, 'params--------');

      try {
        let { code, rows, total } = await dealerApi.list(params);
        if (code == 200) {
          this.tableData = rows;
          this.page.total = total;
        }
      } catch (error) {
        console.log(error);
      } finally {
        this.loading = false;
      }

    },
    // 重置
    handelResetSearch() {

      console.log('重置');
      this.searchParams = {
        ...initParams(SearchColumns),
      }
    },
    // 判断状态
    judgeStatus(status) {
      // 单据状态0=自由态，1=审批中，2=已审核，3=已驳回
      let statusName = '';
      switch (status) {
        case '0':
          statusName = '自由态';
          break;
        case '1':
          statusName = '审批中';
          break;
        case '2':
          statusName = '已审核';
          break;
        case '3':
          statusName = '已驳回';
          break;
        default:
          break;
      }

      return statusName;
    },
    // 刷新
    handleRefresh() {
      this.handelSearch();
    },
    handleSizeChange(e) {
      this.page.pageSize = e;
      this.handelSearch();
    },
    handleCurrentChange(e) {
      this.page.pageNum = e;
      this.handelSearch();
    },

    // 选择列表
    handleSelect(selection, row) {
      console.log('selection/////////', selection, 'row/////////', row);
      this.checkedList = [...selection];
    },
    // 新增、编辑授权信息
    handleOpenAddDialog(rows) {
      const { setVisible, setFormData } = this.$refs.addDialogRef;
      setFormData(rows);
      setVisible(true);

    },
    // 查看
    handleOpenSeeDialog(rows) {
      const { setVisible, setFormData } = this.$refs.seeDialogRef;
      setFormData(rows);
      setVisible(true);
    },
    // 删除
    handleDelDialog(rows) {
      let { id } = rows;

      this.$confirm('此操作将删除该条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          this.loading = true;
          let { code, msg } = await dealerApi.remove({ id });
          if (code == 200) {
            this.handleRefresh();
          }
        } catch (error) {
          console.log(error);
        } finally {
          this.loading = false;
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },
    // 提交OA
    async handleSubmit(row) {
      try {
        // name:工号   nickName:名字
        const { name, nickName } = this.$store.state.user;

        const { id, authorizedProductsCode,dealerName,authorizedProductsName,authorizedAreaName   } = row;

        let data = {
          authorizedProductsCode,
          id,
          createPerson: nickName,
          createBy: name,
          date: new Date().Format(),
          dealerName,
          authorizedProductsName,
          authorizedAreaName
        }

        this.loading = true;
        let { code, msg } = await dealerApi.submitOA(data);
        if (code == 200) {
          this.handleRefresh();
        }
      } catch (error) {
        console.log(error);
      } finally {
        this.loading = false;

      }



    },
    // 下载
    async handleDownload(row) {
      console.log('下载', row);
      try {
        const { id, authorizedProductsCode, dealerName, authorizedAreaName, authorizedProductsName } = row;

        const data = {
          dealerName,
          authorizedAreaName,
          authorizedProductsName,
          id,
          authorizedProductsCode,
        }

        // await this.download('/dealer/download', data, `授权书${new Date().getTime()}.doc`);
        let file = await dealerApi.download(data)
        let blob = new Blob([file], {
          type: `application/msword` //word文档为msword,pdf文档为pdf，msexcel 为excel
        });
        let objectUrl = URL.createObjectURL(blob);
        let link = document.createElement("a");
        let fname = `授权书.doc`; //下载文件的名字+后缀名
        link.href = objectUrl;
        link.setAttribute("download", fname);
        document.body.appendChild(link);
        link.click();

      } catch (error) {
        console.log(error);
      } finally { }
    },

  },
  created() {
    this.handelSearch();
    console.log(this.$store.state.user, 'this.$store.state.user');
  }

}
</script>

<style lang="scss" scoped>
.dealerAuthorization {
  width: calc(100% - 24px);
  height: 100%;
  margin: 10px;
  padding: 10px;
  box-sizing: border-box;

  .da-table {
    width: 100%;
    margin: 20px 0 0 0;
  }
}
</style>