<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="区域公司" prop="deptOne">
        <el-select v-model="queryParams.deptOne" placeholder="事业部" clearable size="small" @change="oneChange">
          <el-option
            v-for="dict in deptOptions"
            :key="dict.deptId"
            :label="dict.deptName"
            :value="dict.deptId"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="大区" prop="deptTwo">
        <el-select :disabled="twoIsDisabled" v-model="queryParams.deptTwo" placeholder="大区" clearable size="small"  @change="oneTwoChange">
          <el-option
            v-for="dict in deptTwoOptions"
            :key="dict.deptId"
            :label="dict.deptName"
            :value="dict.deptId"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="销售部" prop="deptThree">
        <el-select :disabled="threeIsDisabled" v-model="queryParams.deptThree" placeholder="销售部" clearable size="small" @change="onInput">
          <el-option
            v-for="dict in deptThreeOptions"
            :key="dict.deptId"
            :label="dict.deptName"
            :value="dict.deptId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="门店名称" prop="receiveShopName">
        <el-input
          v-model="queryParams.receiveShopName"
          placeholder="请输入门店名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
          @input="onInput"
        />
      </el-form-item>
      <el-form-item label="物品状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择物品状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
            v-if="dict.dictValue != '0'"
          />
        </el-select>
      </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-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['guide:sign:import']"
          v-if="name == query.name"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['guide:sign:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="signList" max-height="550">
      <el-table-column label="公司" align="center" prop="deptOne" width="120" />
      <el-table-column label="大区" align="center" prop="deptTwo" width="120" />
      <el-table-column label="销售部" align="center" prop="deptThree" width="200" />
      <el-table-column label="接收门店名称" align="center" prop="receiveShopName" width="280"/>
      <el-table-column label="接收门店编码" align="center" prop="receiveShopCode" width="120" />
      <el-table-column label="发放人" align="center" prop="issuer" />
      <el-table-column label="发放人编码" align="center" prop="issuerCode" width="90"/>
      <el-table-column label="物料名称" align="center" prop="publicityName" width="220" />
      <el-table-column label="物料类型" align="center" prop="publicityType" width="190"/>
      <el-table-column label="发放数量" align="center" prop="extend" width="120"/>
      <el-table-column label="物品发放时间" align="center" prop="issuingTime" width="160"/>
      <el-table-column label="物品目前状态" align="center" prop="status" width="120">
        <template slot-scope="scope">
<!--          <span>{{statusFormat(scope.row)}}</span>-->
          <dicts-tag :options="statusOptions" :value="scope.row.status.toString()"/>
        </template>
      </el-table-column>
      <el-table-column label="签收导购名称" align="center" prop="signGuidename" width="120"/>
      <el-table-column label="签收导购编码" align="center" prop="signGuidecode" width="120" />
      <el-table-column label="签收时间" align="center" prop="signTime" width="180"/>
      <!--      <el-table-column label="发货图片id" align="center" prop="grantImgid" />-->
      <!--      <el-table-column label="签收图片id" align="center" prop="signImgid" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="120">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="handleDetail(scope.row)"
            v-hasPermi="['guide:sign:query']"
          >详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog class="upload" :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <div style="margin-bottom: 14px;">
        <el-link type="primary" style="font-size:14px" @click="importTemplate">下载模板</el-link>
      </div>

      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        :data={taskId:queryParams.taskId}
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>

        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm" :disabled="upload.isUploading">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
    import { listSign, getSign, delSign,cancel, addSign, updateSign, exportSign,importProduct,listStore,addissuerStore,issuerStoreDetail,updateissuerStore,importTemplate } from "@/api/guide/sign";
    import { getToken } from "@/utils/auth";
    import { childListDept } from "@/api/system/dept";
    export default {
        name: "Sign",
        components: {
        },
        data() {
            return {
                // 遮罩层
                loading: true,
                // 导出遮罩层
                exportLoading: false,

                // 显示搜索条件
                showSearch: true,
                // 总条数
                total: 0,
                // 物料签收表格数据
                signList: [],

                upload: {
                    // 是否显示弹出层（用户导入）
                    open: false,
                    // 弹出层标题（用户导入）
                    title: "",
                    // 是否禁用上传
                    isUploading: false,
                    // 是否更新已经存在的用户数据
                    updateSupport: 0,
                    // 设置上传的请求头部
                    headers: { Authorization: "Bearer " + getToken() },
                    // 上传的地址
                    url: process.env.VUE_APP_BASE_API + "/common/uploadsign",
                    loadProgress: 10,
                },
                // 查询参数
                queryParams: {
                    pageNum: 1,
                    pageSize: 10,
                    deptOne: null,
                    deptTwo: null,
                    deptThree: null,
                },

                deptOptions:[],
                deptTwoOptions:[],
                deptThreeOptions:[],
                twoIsDisabled:true,
                threeIsDisabled:true,
                statusOptions:[],
                name:'',
                query:{},
            };
        },
        created() {
            this.getDicts("guide_sign_status").then(response => {
                this.statusOptions = response.data;
            });
            this.name = this.$store.state.user.name;
            this.query = this.$route.query;
            this.getChildList(1,1);
            this.getList();
        },
        methods: {
            onInput(){
                this.$forceUpdate()
            },
            getChildList(parentId,level){
                childListDept(parentId).then(response=>{
                    if(level==1){
                        this.deptOptions = response.data;
                    }else if(level == 2){
                        this.deptTwoOptions = response.data;
                    }else if(level == 3){
                        this.deptThreeOptions = response.data;
                    }

                })
            },
            oneChange(val){
                console.log(val)
                this.$forceUpdate();
                if(val==""){
                    this.twoIsDisabled=true;
                    this.threeIsDisabled=true;
                }else{
                    this.getChildList(val,2)
                    this.twoIsDisabled=false;
                    this.threeIsDisabled=true;
                }
                this.queryParams.deptTwo="";
                this.queryParams.deptThree="";
            },
            oneTwoChange(val){
                this.$forceUpdate();
                console.log(val)
                if(val==""){
                    this.threeIsDisabled=true;
                }else{
                    this.getChildList(val,3)
                    this.threeIsDisabled=false;
                }
                this.queryParams.deptThree="";
            },
            statusFormat(row){
                return this.selectDictLabel(this.statusOptions, row.status);
            },
            /** 查询物料签收列表 */
            getList() {
                this.loading = true;
                this.queryParams.taskId =this.query.taskId;
                listSign(this.queryParams).then(response => {
                    this.signList = response.rows;
                    this.total = response.total;
                    this.loading = false;
                });
            },

            /** 搜索按钮操作 */
            handleQuery() {
                this.queryParams.pageNum = 1;
                this.getList();
            },
            /** 重置按钮操作 */
            resetQuery() {
                this.resetForm("queryForm");
                this.handleQuery();
            },

            handleDetail(row){
                this.$router.push({path:'/material/signDetail',query:{id:row.id,extend:this.query.extend,taskId:this.query.taskId,name:this.query.name}});
            },

            /** 导出按钮操作 */
            handleExport() {
                const queryParams = this.queryParams;
                this.$confirm('是否确认导出所有物料签收数据项?', "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(() => {
                    this.exportLoading = true;
                    return exportSign(queryParams);
                }).then(response => {
                    // this.downloads(response.msg);
                  window.location.href = process.env.VUE_APP_BASE_API + "/common/download?fileName=" + encodeURI(response.msg) + "&delete=" + true;
                    this.exportLoading = false;
                }).catch(() => {});
            },
            handleImport() {
                this.upload.title = "物料签收导入";
                this.upload.open = true;
            },
            /** 下载模板操作 */
            importTemplate() {
                importTemplate().then(response => {
                  window.location.href = process.env.VUE_APP_BASE_API + "/common/download?fileName=" + encodeURI(response.msg) + "&delete=" + true;
                });
            },
            // 文件上传中处理
            handleFileUploadProgress(event, file, fileList) {
                this.upload.isUploading = true;
                this.upladLoading = this.$loading({
                    lock: true,
                    text: '拼命上传中',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
            },
            // 文件上传成功处理
            handleFileSuccess(response, file, fileList) {
                let query = this.$route.query;
                if(response.code==200){
                    let data = {"url":response.url,taskId:query.taskId,extend:query.extend};
                    importProduct(data).then(res => {
                        this.upload.open = false;
                        this.upload.isUploading = false;
                        this.upladLoading.close();
                        this.$refs.upload.clearFiles();
                        this.$alert(res.msg, "导入结果", { dangerouslyUseHTMLString: true });
                    })
                }else{
                    this.upload.open = false;
                    this.upload.isUploading = false;
                    this.upladLoading.close();
                    this.$refs.upload.clearFiles();
                    this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
                }
                this.getList();
            },
            // 提交上传文件
            submitFileForm() {
                this.$refs.upload.submit();
            },
        }


    };
</script>
<style lang="scss" scoped>
  .line-ht36{
    line-height: 36px;
  }
  .required:before{
    content: "*";
    color: #ff4949;
    margin-right: 4px;
  }
  .required{
    font-size: 14px;
    color: #606266;
    font-weight: 700;
  }
</style>
<style lang="scss">
  .el-upload-list__item{
    div{
      height: 100%;
    }
  }
</style>
