<template>
  <div class="app-container">
    <el-card shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
      </div>
      <div style="margin-top: 15px">
        <el-form
          size="small"
          :model="queryParams"
          ref="queryForm"
          :inline="true"
          @submit.native.prevent
        >
          <!-- <el-form-item label="姓名">
            <el-input v-model="queryParams.name" placeholder="请输入" />
          </el-form-item> -->
          <el-form-item label="手机号">
            <el-input v-model="queryParams.phone" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="queryParams.status"
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in optionList"
                :key="item.key"
                :label="item.value"
                :value="item.key"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="领取时间">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              value-format="yyyy-MM-dd HH:mm:ss"
              align="right"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="['00:00:00', '23:59:59']"
            >
            </el-date-picker>
          </el-form-item>
          <el-button type="primary" @click="handleSearchList" size="small">
            查询
          </el-button>
        </el-form>
      </div>
    </el-card>
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>
      <div class="btn-add">
        <el-button
          @click="handleImport"
          class="btn-adds"
          size="small"
          type="success"
        >
          导入
        </el-button>
        <el-button
          @click="handleExport"
          class="btn-adds"
          size="small"
          type="warning"
        >
          导出
        </el-button>
        <el-button
          @click="handleAdd"
          class="btn-adds"
          size="small"
          type="success"
          >手动添加</el-button
        >
        <el-button
          @click="handleDelete(false)"
          class="btn-del"
          size="small"
          type="success"
          >一键删除</el-button
        >
        <el-button
          @click="handleImportStatus"
          class="btn-del"
          size="small"
          type="success"
          >一键发货</el-button
        >
      </div>
    </el-card>
    <!-- @selection-change="handleSelectionChange" -->
    <el-table style="width: 100%" class="table-container" :data="dataList">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column
        label="序号"
        align="center"
        type="index"
      ></el-table-column>
      <el-table-column
        label="姓名"
        prop="name"
        align="center"
        width="80px"
      ></el-table-column>
      <el-table-column
        label="手机号"
        prop="phone"
        align="center"
        width="120px"
      ></el-table-column>
      <el-table-column
        label="单位"
        align="center"
        prop="unit"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="收货姓名"
        prop="otherName"
        align="center"
        width="80px"
      ></el-table-column>
      <el-table-column
        label="收货手机号"
        prop="otherPhone"
        align="center"
        width="120px"
      ></el-table-column>
      <el-table-column
        label="收货地址"
        align="center"
        prop="address"
      ></el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="100px"
      ></el-table-column>
      <el-table-column
        label="领取状态"
        align="center"
        prop="status"
        width="80px"
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status == 0" type="danger">未领取</el-tag>
          <el-tag v-else-if="scope.row.status == 1">已领取</el-tag>
          <el-tag v-else type="warning">已发货</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="领取时间" align="center" prop="receiveTime">
        <!-- <template slot-scope="scope">
          <span v-if="scope.row.status == '1'">
            {{ scope.row.receiveTime }}
          </span>
          <span v-else></span>
        </template> -->
      </el-table-column>
      <el-table-column
        label="快递公司"
        align="center"
        prop="trackingUnit"
      ></el-table-column>
      <el-table-column
        label="快递单号"
        align="center"
        prop="trackingNumber"
      ></el-table-column>
      <el-table-column
        label="操作"
        class-name="small-padding fixed-width"
        align="center"
      >
        <template slot-scope="scope">
          <el-button
            @click="handleStatus(scope.row)"
            type="text"
            size="mini"
            style="color:#41b584"
            :disabled="scope.row.status == '0'"
            >发货</el-button
          >
          <el-button @click="handleUpdate(scope.row)" type="text" size="mini"
            >编辑</el-button
          >
          <el-button
            @click="handleDelete(scope.row)"
            type="text"
            size="mini"
            class="text-danger"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getDataList"
    />
    <!-- 添加修改 -->
    <el-dialog :title="title" :visible.sync="dialogVisible" width="25%">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" :disabled="form.status == 1"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="form.phone"
            :disabled="form.status == 1"
            maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="收货手机号"
          prop="otherPhone"
          v-if="form.status == 1"
        >
          <!-- v-if="title == '修改名单'" -->
          <el-input v-model="form.otherPhone" maxlength="11"></el-input>
        </el-form-item>
        <el-form-item label="收货地址" prop="address" v-if="form.status == 1">
          <el-input v-model="form.address" type="textarea" autosize></el-input>
        </el-form-item>
        <el-form-item label="领取状态" prop="status" v-if="form.status">
          <el-select v-model="form.status" placeholder="请选择" disabled>
            <el-option
              v-for="item in optionList"
              :key="item.key"
              :label="item.value"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 发货 -->
    <el-dialog title="发货" :visible.sync="statusDialogVisible" width="25%">
      <el-form
        ref="statusForm"
        :model="statusForm"
        :rules="statusRules"
        label-width="90px"
      >
        <el-form-item label="快递公司" prop="trackingUnit">
          <el-input v-model="statusForm.trackingUnit"></el-input>
        </el-form-item>
        <el-form-item label="快递单号" prop="trackingNumber">
          <el-input v-model="statusForm.trackingNumber"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="statusDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitStatusForm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="
          upload.url + '?activityId=' + queryParams.activityId + '&unit=' + unit
        "
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-link
            style="font-size:16px;font-weight:700"
            @click="importTemplate"
            >下载模板</el-link
          >
        </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">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 发货文件 -->
    <el-dialog
      :title="uploadStatus.title"
      :visible.sync="uploadStatus.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="uploadStatus"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="uploadStatus.headers"
        :action="uploadStatus.url"
        :disabled="uploadStatus.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileStatusSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileStatusForm"
          >确 定</el-button
        >
        <el-button @click="uploadStatus.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  userList,
  orderDelete,
  aUserCreate,
  aUserUpdate,
  aUserDelete
} from '@/api/index';
import { getToken } from '@/utils/auth';
export default {
  name: 'Index',
  data() {
    var checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('手机号不能为空'));
      } else {
        const reg = /^1[3|4|5|7|8|9][0-9]\d{8}$/;
        console.log(reg.test(value));
        if (reg.test(value)) {
          callback();
        } else {
          return callback(new Error('请输入正确的手机号'));
        }
      }
    };
    return {
      optionList: [
        {
          key: '0',
          value: '未领取'
        },
        {
          key: '1',
          value: '已领取'
        },
        {
          key: '2',
          value: '已发货'
        }
      ],
      dateRange: [],
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/aUser/importDate'
      },
      // 发货文件参数
      uploadStatus: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/aUser/batchShipment'
      },
      unit: '',
      // 选中数组
      ids: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        activityId: null
      },
      queryPost: {
        name: '',
        phone: '',
        unit: ''
      },
      total: 0,
      dataList: [],
      dialogVisible: false,
      statusDialogVisible: false,
      rowItem: {},
      title: '',
      form: {},
      statusForm: {},
      rules: {
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        // phone: [{ required: true, message: '请输入', trigger: 'blur' }],
        phone: [{ required: true, validator: checkPhone, trigger: 'blur' }],
        unit: [{ required: true, message: '请输入', trigger: 'blur' }],
        // otherPhone: [{ required: true, message: '请输入', trigger: 'blur' }],
        otherPhone: [
          { required: true, validator: checkPhone, trigger: 'blur' }
        ],
        address: [{ required: true, message: '请输入', trigger: 'blur' }]
      },
      statusRules: {
        trackingUnit: [{ required: true, message: '请输入', trigger: 'blur' }],
        trackingNumber: [{ required: true, message: '请输入', trigger: 'blur' }]
      }
    };
  },
  methods: {
    importTemplate() {
      window.location.href =
        'http://124.70.138.50:9000/pic/20210910/1436156274994712576.xlsx';
    },
    handleSearchList() {
      this.queryParams.pageNum = 1;
      this.getDataList();
    },
    getDataList() {
      if (this.dateRange == [] || !this.dateRange) {
        delete this.queryParams.startTime;
        delete this.queryParams.endTime;
      } else {
        this.queryParams.startTime = this.dateRange[0];
        this.queryParams.endTime = this.dateRange[1];
      }
      const query = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize
      };
      userList(this.queryParams, query).then(({ data }) => {
        this.dataList = data.list;
        this.total = data.total;
      });
    },
    // 添加
    handleAdd() {
      this.form = {
        activityId: this.queryParams.activityId, // 活动id
        unit: this.unit // 单位
      };
      this.resetForm('form');
      this.dialogVisible = true;
      this.title = '添加名单';
    },
    handleStatus(row) {
      this.statusForm = {};
      this.resetForm('statusForm');
      this.statusDialogVisible = true;
      this.rowItem = Object.assign({}, row);
      if (row.status == 2) {
        this.statusForm = Object.assign({}, row);
      }
    },
    // 编辑
    handleUpdate(row) {
      this.resetForm('form');
      this.form = Object.assign({}, row);
      this.dialogVisible = true;
      this.title = '修改名单';
    },
    // 提交
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.title == '修改名单') {
            aUserUpdate(this.form).then(response => {
              this.msgSuccess('修改成功');
              this.dialogVisible = false;
              this.getDataList();
            });
          } else {
            aUserCreate(this.form).then(response => {
              console.log(response);
              this.msgSuccess('新增成功');
              this.dialogVisible = false;
              this.getDataList();
            });
          }
        }
      });
    },
    submitStatusForm() {
      this.$refs['statusForm'].validate(valid => {
        if (valid) {
          console.log(this.rowItem);
          console.log(this.statusForm);
          let query =
            this.rowItem.status == '2'
              ? this.statusForm
              : Object.assign({}, this.rowItem, this.statusForm);
          query.status = '2';
          aUserUpdate(query).then(response => {
            this.msgSuccess('修改成功');
            this.statusDialogVisible = false;
            this.getDataList();
          });
        }
      });
    },
    // 导出
    handleExport() {
      this.$confirm('是否确认导出所有数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        window.location.href =
          process.env.VUE_APP_BASE_API +
          '/aUser/export' +
          this.changeParam(this.queryParams);
        //   process.env.VUE_APP_BASE_API + '/aUser/export?' + this.queryParams;
        // this.queryParams.activityId;
      });
    },
    changeParam(param) {
      return JSON.stringify(param)
        .replace(/:/g, '=')
        .replace(/,/g, '&')
        .replace(/{/g, '?')
        .replace(/}/g, '')
        .replace(/"/g, '');
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = '导入名单';
      this.upload.open = true;
    },
    handleImportStatus() {
      this.uploadStatus.title = '发货管理';
      this.uploadStatus.open = true;
    },
    // 发货文件上传成功处理
    handleFileStatusSuccess(response, file, fileList) {
      this.uploadStatus.open = false;
      this.uploadStatus.isUploading = false;
      this.$refs.uploadStatus.clearFiles();
      this.$alert(response.data, '发货结果', {
        dangerouslyUseHTMLString: true
      });
      this.getDataList();
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
      this.uploadStatus.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.data, '导入结果', {
        dangerouslyUseHTMLString: true
      });
      this.getDataList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    submitFileStatusForm() {
      this.$refs.uploadStatus.submit();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      if (!row && !this.total) return this.msgInfo('暂无数据');
      const val = row ? `删除 '${row.name}' 这条` : '清空所有';
      this.$confirm(`确认${val}数据?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const query = !row.id
            ? { id: this.queryParams.activityId }
            : { ids: [row.id] };
          return aUserDelete(query);
        })
        .then(() => {
          this.getDataList();
          this.msgSuccess('删除成功');
        });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
    }
  },
  created() {
    // const { id } = this.$route.query;
    // if (!id) {
    //   this.msgError('无ID');
    //   this.$router.go(-1);
    //   return;
    // }
    const { row } = this.$route.query;
    const query = JSON.parse(row);
    if (!query || !query.id) {
      this.msgError('无ID');
      this.$router.go(-1);
      return;
    }
    console.log(query);
    this.unit = query.unit;
    this.queryParams.activityId = query.id;
    this.getDataList();
  }
};
</script>
<style lang="scss">
.el-date-table td.in-range div {
  background-color: #d2f9e8 !important;
}
</style>
<style lang="scss" scoped>
/deep/.el-dialog__header {
  .el-dialog__title {
    color: #000 !important;
  }
}
</style>
