<template>
  <template-page
    ref="pageRef"
    :getList="getList"
    :operation="operation()"
    :optionsEvensGroup="optionsEvensGroup"
    :exportList="exportList"
    :columnParsing="columnParsing"
    :tableAttributes="tableAttributes"
    :tableEvents="tableEvents"
    :operationColumnWidth="200"
    :replaceOrNotMap="false"
  >
    <!-- 弹窗 -->
    <el-dialog
      title="提货人档案"
      :visible.sync="dialogForm"
      width="40%"
      :show-close="false"
      :close-on-click-modal="false"
    >
      <el-form ref="addForm" :rules="rules" :model="addForm" label-width="120px">
        <el-form-item label="经销商名称" prop="customerId">
          <!-- <el-select v-model="addForm.customerId" placeholder="名称">
            <el-option
              v-for="item in dealerList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select> -->
          <el-input disabled v-model="addForm.customerName"></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="提货人姓名" prop="takerName">
              <el-input v-model="addForm.takerName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号码" prop="identity">
              <el-input v-model="addForm.identity"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="addForm.phone"></el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-row :gutter="0">
              <el-col :span="14">
                <el-form-item label="验证码" prop="code">
                  <el-input v-model="addForm.code" />
                </el-form-item>
              </el-col>
              <el-col :span="9">
                <el-button v-show="show" type="info" @click="getCodeFn">获取验证码</el-button>
                <el-button v-show="!show" :style="{
                    backgroundColor: '#409eff',
                    border: '0',
                  }" type="info">{{ count }}s后重新获取</el-button>
              </el-col>
            </el-row>
          </el-col> -->
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="有效期" prop="expireTime">
              <el-date-picker
                v-model="addForm.expireTime"
                type="date"
                placeholder="选择日期"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备用电话" prop="sparePhone">
              <el-input v-model="addForm.sparePhone"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="上传提货人附件" prop="fileUrl">
          <fileUpload :fileList="fileList" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelFn">取 消</el-button>
        <el-button v-if="showOK" type="primary" @click="addDataFn">确 定</el-button>
      </div>
    </el-dialog>
  </template-page>
</template>

<script>
import TemplatePage from '@/components/template/template-page-1.vue'
import { mapGetters } from 'vuex'
import {
  getList,
  addDataList,
  getCodeApi,
  stopTaker,
  deleDataList,
  v2TakerRecordList,
  v2TakerRecordListExport
} from '@/api/basic_data/taker'
import { getDealerList } from '@/api/basic_data/dealer'
import { downloadFiles } from '@/utils/util'
import fileUpload from '@/components/Common/file-upload.vue'
export default {
  components: {
    fileUpload,
    TemplatePage
  },
  computed: {
    ...mapGetters(['customerId', 'customerName']),
    exParams() {
      return {
        customerName: this.searchForm.customerName,
        takerName: this.searchForm.takerName,
        phoneKeyword: this.searchForm.phoneKeyword
      }
    }
  },
  data() {
    return {
      // 事件组合
      optionsEvensGroup: [
        [
          [
            {
              name: '新增',
              click: () => {
                this.addFn()
              },
              isRole: this.$checkBtnRole('add', this.$route.meta.roles)
            }
          ]
        ]
      ],
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: false
      },
      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      recordSelected: [],

      baseURL: process.env.VUE_APP_BASE_API,
      isCollapse: true,
      fileList: [],
      listLoading: false, // 列表加载loading
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页数量
      listTotal: 0, // 列表总数
      addForm: {
        customerName: '',
        takerName: '',
        identity: '',
        phone: '',

        sparePhone: '',
        expireTime: '',
        code: ''
      },
      show: true, //验证码
      count: '',
      timer: null,

      rules: {
        customerId: [{ required: false, message: '请选择经销商', trigger: 'blur' }],
        takerName: [{ required: true, message: '请输入提货人姓名', trigger: 'blur' }],

        phone: [
          {
            required: true,
            message: '请输入联系电话',
            trigger: 'blur'
          },
          {
            required: true,
            pattern: /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/,
            message: '联系电话格式不正确',
            trigger: 'blur'
          }
        ],
        sparePhone: [
          {
            required: false,
            pattern: /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/,
            message: '请输入备用电话',
            trigger: 'blur'
          }
        ],
        expireTime: [{ required: true, message: '有效期不能为空', trigger: 'blur' }]
        // code: [{ required: true, message: "验证码不能为空", trigger: "blur" }],
      },

      dialogForm: false,
      dataList: [],
      searchForm: {
        customerName: '',
        takerName: '',
        phoneKeyword: ''
      },
      dealerList: [],
      id: '', //重建之前的Id
      showOK: true
    }
  },
  created() {
    // this.getDataList()
    // await this.getDealerDataList({ pageNum: 1, pageSize: 10 });
  },
  methods: {
    // 列表请求函数
    getList: v2TakerRecordList,
    // 列表导出函数
    exportList: v2TakerRecordListExport,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },
    operation() {
      return (h, { row, index, column }) => {
        return (
          <div class="operation-btns">
            <el-button
              size="mini"
              type="text"
              onClick={async () => {
                this.seeFn(row)
              }}
            >
              查看
            </el-button>

            {this.$checkBtnRole('del', this.$route.meta.roles) ? (
              <el-popconfirm
                onOnConfirm={async () => {
                  this.deleFn(row.id)
                }}
                title="是否确定需要删除该项内容?"
              >
                <el-button slot="reference" size="mini" type="text">
                  删除
                </el-button>
              </el-popconfirm>
            ) : (
              ''
            )}

            {row.flag === 1 ? (
              <el-button
                size="mini"
                type="text"
                onClick={async () => {
                  this.stopFn(row.id)
                }}
              >
                停用
              </el-button>
            ) : (
              ''
            )}
            {row.flag === 2 ? (
              <el-button
                size="mini"
                type="text"
                onClick={async () => {
                  this.rebuild(row)
                }}
              >
                重建
              </el-button>
            ) : (
              ''
            )}
          </div>
        )
      }
    },

    //重建
    rebuild(data) {
      this.showOK = true
      this.id = data.id
      this.addForm = {
        customerName: data.customerName,
        takerName: data.takerName,
        identity: data.identity,
        phone: data.phone,

        sparePhone: data.sparePhone,
        expireTime: '',
        code: ''
      }
      this.fileList = []
      this.dialogForm = true
    },
    //删除
    async deleFn(ids) {
      await deleDataList({ ids })
      this.$message.success('删除成功')
      // this.getDataList()
      this.$refs.pageRef.refreshList()
    },
    //查看
    seeFn(data) {
      this.showOK = false
      this.addForm = data
      this.fileList = []
      this.dialogForm = true
    },

    //取消
    cancelFn() {
      if (this.addForm.id) {
        this.addForm = {
          takerName: '',
          identity: '',
          phone: '',

          sparePhone: '',
          expireTime: '',
          code: ''
        }
      } else {
        this.$refs.addForm.resetFields()
      }
      this.count = 0
      this.dialogForm = false
    },
    //上传
    handlefile(response, file, fileList) {
      console.log(response, file, fileList)
    },
    // //导出
    // exportFn() {
    //   let screenData = {
    //     customerName: this.searchForm.customerName,
    //     takerName: this.searchForm.takerName,
    //   };
    //   downloadFiles("/taker-record/export", screenData);
    // },
    //停用提货人档案
    async stopFn(id) {
      await stopTaker({ id })
      this.$message.success('成功')
      // this.getDataList()
      this.$refs.pageRef.refreshList()
    },
    //获取验证码
    async getCodeFn() {
      const res = await getCodeApi({ mobile: this.addForm.phone })
      const TIME_COUNT = 60 //倒计时的初始值
      this.count = TIME_COUNT
      this.show = false
      this.timer = setInterval(() => {
        if (this.count > 0 && this.count <= TIME_COUNT) {
          this.count--
        } else {
          this.show = true
          clearInterval(this.timer)
          this.timer = null
        }
      }, 1000)
    },
    //获取经销商数据
    async getDealerDataList(data) {
      const res = await getDealerList(data)
      this.dealerList = res.data.records
    },
    //获取列表数据
    async getDataList() {
      let params = {
        customerName: this.searchForm.customerName,
        takerName: this.searchForm.takerName,
        phoneKeyword: this.searchForm.phoneKeyword,
        pageNum: this.currentPage,
        pageSize: this.pageSize
      }
      let res = await getList(params)
      this.dataList = res.data.records
      this.listTotal = res.data.total
    },
    //搜索功能
    async searchFn() {
      this.currentPage = 1
      await this.getDataList()
    },
    //重置
    clearFn() {
      this.$refs.searchForm.resetFields()
    },

    // 更改每页数量
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.getDataList()
    },
    // 更改当前页
    handleCurrentChange(val) {
      this.currentPage = val
      this.getDataList()
    },
    //新增
    async addDataFn() {
      await this.$refs.addForm.validate()

      // const res = this.dealerList.filter(
      //   (v) => v.id === this.addForm.customerId
      // )[0];
      // console.log(res);

      if (this.fileList.length == 1) {
        await addDataList({
          ...this.addForm,

          customerId: this.customerId,
          fileName: this.fileList[0].name,
          fileUrl: this.fileList[0].url
        })
      } else {
        await addDataList({
          ...this.addForm,
          customerId: this.customerId,
          fileName: '',
          fileUrl: ''
        })
      }

      if (this.id) {
        await deleDataList({ ids: this.id })
      }

      this.$message.success('新增成功')
      this.id = ''
      // this.addForm = {
      //   customerId: "",
      //   takerName: "",
      //   identity: "",
      //   phone: "",

      //   sparePhone: "",
      //   expireTime: "",
      //   code: "",
      // };
      this.count = 0
      // this.getDataList()
      this.$refs.pageRef.refreshList()
      this.dialogForm = false
    },
    addFn() {
      this.addForm = {
        customerName: this.customerName,
        takerName: '',
        identity: '',
        phone: '',
        sparePhone: '',
        expireTime: '',
        code: ''
      }
      this.fileList = []
      this.showOK = true
      this.dialogForm = true
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-date-editor {
  width: 100%;
}
::v-deep .el-select {
  width: 100%;
}
::v-deep .el-col-9 .el-button {
  padding: 5px;
  margin: 6px;
}
::v-deep .el-dialog__header {
  background-color: #dddddd;
}
.base {
  padding: 20px 20px 0;
}
.table {
  margin-top: 12px;
}
.right {
  float: right;
}
</style>
