<template>
  <div class="app-container">
    <div v-if="showHistory">
      <!-- <el-card class="box-card">
      <el-row>
        <h4>通用经销商工程机押金比例配置</h4>
        <h4>
          工程机押金比例配置
          <input
            type="text"
            class="inp"
          />%通用工程押金比例配置适用于,没有单独配置工程机押金比例的经销商.
        </h4>
      </el-row>
    </el-card> -->
      <!-- 筛选条件 -->
      <Collapse :screen-form="searchForm">
        <template #right_btn>
          <el-button size="mini" @click="clearFn">清空</el-button>
          <el-button size="mini" type="primary" @click="searchFn">搜索</el-button>
        </template>
        <template #search>
          <el-form ref="searchForm" :model="searchForm" label-width="100px" size="mini" label-position="left">
            <el-row :gutter="20">
              <el-col :xs="24" :sm="12" :lg="6">
                <el-form-item label="经销商名称" prop="customerName">
                  <el-input v-model="searchForm.customerName" placeholder="请输入经销商名称"></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :lg="6">
                <el-form-item label="状态" prop="currentStatus">
                  <el-select class="selectStyle" v-model="searchForm.currentStatus" placeholder="请选择">
                    <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </Collapse>

      <!-- 按钮 -->
      <div class="btn-group clearfix">
        <div class="fl">
          <el-button v-if="$checkBtnRole('add', $route.meta.roles)" type="primary" size="mini" @click="addFn"
            >新增</el-button
          >
        </div>
        <div class="fr">
          <el-button type="primary" size="mini" @click="downLoadFn">模板</el-button>
          <el-upload
            class="import-btn"
            action=""
            :http-request="handleImport"
            :file-list="importFileList"
            :show-file-list="false"
          >
            <el-button type="primary" size="mini">批量导入</el-button>
          </el-upload>
        </div>
      </div>

      <div class="mymain-container">
        <!-- 列表 -->
        <div class="table">
          <el-table
            v-loading="listLoading"
            :data="dataList"
            element-loading-text="Loading"
            border
            fit
            highlight-current-row
            stripe
          >
            <el-table-column
              align="left"
              label="经销商编码"
              prop="customerNumber"
              min-width="160"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <CopyButton :copyText="scope.row.customerNumber" />
                <span>{{ scope.row.customerNumber }}</span>
              </template>
            </el-table-column>
            <el-table-column align="left" label="经销商名称" prop="customerName" min-width="260" show-overflow-tooltip>
              <template slot-scope="scope">
                <CopyButton :copyText="scope.row.customerName" />
                <span>{{ scope.row.customerName }}</span>
              </template>
            </el-table-column>
            <el-table-column align="left" label="押金比例" prop="rate" min-width="100" show-overflow-tooltip />
            <el-table-column align="left" label="押金" prop="amount" min-width="100" show-overflow-tooltip />
            <el-table-column align="left" label="状态" prop="currentStatus" min-width="100" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-tag size="mini" type="info" v-if="scope.row.currentStatus == '未开始'">未开始</el-tag>
                <el-tag size="mini" type="success" v-if="scope.row.currentStatus == '生效中'">生效中</el-tag>
                <el-tag size="mini" type="danger" v-if="scope.row.currentStatus == '已结束'">已结束</el-tag>
              </template>
            </el-table-column>
            <el-table-column align="left" label="开始时间" prop="startTime" min-width="160" show-overflow-tooltip />
            <el-table-column align="left" label="结束时间" prop="endTime" min-width="160" show-overflow-tooltip />
            <el-table-column align="left" label="备注" prop="remark" min-width="160" show-overflow-tooltip />
            <el-table-column align="left" label="创建人" prop="createBy" min-width="160" show-overflow-tooltip />
            <el-table-column align="left" label="创建时间" prop="createTime" min-width="160" show-overflow-tooltip />
            <el-table-column align="left" label="更新人" prop="updateBy" min-width="160" show-overflow-tooltip />
            <el-table-column align="left" label="更新时间" prop="updateTime" min-width="160" show-overflow-tooltip />
            <el-table-column align="center" label="操作" min-width="200" show-overflow-tooltip fixed="right">
              <template slot-scope="scope">
                <el-button
                  type="text"
                 size="mini"
                  v-if="$checkBtnRole('edit', $route.meta.roles)"
                  @click="editFn(scope.row.id)"
                  >编辑</el-button
                >
                <el-button type="text" size="mini" @click="logFn(scope.row.id)">记录</el-button>
                <el-popconfirm
                class="import-btn"
                  @onConfirm="deleFn(scope.row.id)"
                  v-if="$checkBtnRole('del', $route.meta.roles)"
                  title="这是一段内容确定删除吗？"
                >
                  <el-button type="text" size="mini" slot="reference">删除</el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 分页 -->
        <div class="fr">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="listTotal"
          >
          </el-pagination>
        </div>
      </div>

      <!-- 弹窗 -->
      <el-dialog
        :title="title"
        :visible.sync="showDialog"
        width="30%"
        :show-close="false"
        :close-on-click-modal="false"
      >
        <el-form ref="dialogForm" :model="dialogForm" :rules="rules" label-width="110px" label-position="right">
          <el-form-item label="经销商名称" prop="customerId">
            <el-select class="inputStyle" v-model="dialogForm.customerId" placeholder="请选择" filterable>
              <el-option v-for="item in dealerList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="押金比例" prop="rate">
            <el-input placeholder="请输入押金比例" v-model.number="dialogForm.rate" class="inputStyle">
              <i class="el-input__icon" slot="suffix">% </i>
            </el-input>
          </el-form-item>
          <el-form-item label="" prop="">
            <el-slider class="inputStyle" v-model="dialogForm.rate" :marks="marks"> </el-slider>
          </el-form-item>

          <el-form-item label="押金定额金额" prop="amount">
            <el-input placeholder="请输入押金定额" v-model.number="dialogForm.amount" class="inputStyle"></el-input>
          </el-form-item>
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              class="inputStyle"
              v-model="dialogForm.startTime"
              type="datetime"
              placeholder="选择日期时间"
              default-time="00:00:00"
              value-format="yyyy-MM-dd HH:mm:ss"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间" prop="">
            <el-date-picker
              class="inputStyle"
              v-model="dialogForm.endTime"
              type="datetime"
              placeholder="选择日期时间"
              default-time="23:59:59"
              value-format="yyyy-MM-dd HH:mm:ss"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input
              type="textarea"
              v-model="dialogForm.remark"
              placeholder="请输入备注信息"
              class="inputStyle"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelFn">取 消</el-button>
          <el-button type="primary" @click="addDataListFn">确 定</el-button>
        </div>
      </el-dialog>
    </div>

    <!-- 记录页面 -->
    <DealerDepositHistory :historyId="historyId" @close="handleClose" v-else />
  </div>
</template>

<script>
import {
  getDealerDepositList,
  getDealerDepositAdd,
  getDealerList,
  deleDealerDeposit,
  editDealerDeposit,
  infoDealerDeposit
} from '@/api/basic_data/dealer'
// import { number } from "echarts";
import DealerDepositHistory from './components/dealer_deposit_history'
import { downloadFiles, handleImport } from '@/utils/util'

export default {
  components: {
    DealerDepositHistory
  },
  data() {
    return {
      importFileList: [],
      historyId: '',
      showHistory: true,
      marks: {
        0: '0%',
        20: '20%',
        40: '40%',
        60: '60%',
        80: '80%',
        100: {
          style: {
            width: '36px'
          },
          label: this.$createElement('div', '100%')
        }
      },
      title: '',
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页数量
      listTotal: 0, // 列表
      listLoading: false, // 列表加载loading
      searchForm: {
        customerName: ''
      },
      dialogForm: {
        amount: 0,
        customerId: '',
        customerName: '',
        customerNumber: '',
        endTime: '',

        rate: 0,
        remark: '',
        startTime: ''
      },
      rules: {
        rate: [
          {
            pattern: /^(?:[1-9]?\d|100)$/,
            message: '请输入0-100的数字',
            trigger: 'blur',
            type: 'number',
            required: false
          }
          // {
          //   validator: rate,
          //   trigger: "blur",
          // },
        ],
        amount: [
          {
            trigger: 'blur',
            message: '请输入定额押金',
            type: 'number',
            required: false
          }
          // {
          //   validator: amount,
          //   trigger: "blur",
          // },
        ],
        customerId: [
          {
            message: '请选择经销商名称',
            trigger: 'blur',
            required: true
          }
        ],
        startTime: [
          {
            message: '请选择开始时间',
            trigger: 'blur',
            required: true
          }
        ]
        // endTime: [
        //   {
        //     message: "请选择结束时间",
        //     trigger: "blur",
        //     required: true,
        //   },
        // ],
      },
      showDialog: false,
      dataList: [],
      dealerList: [],
      statusList: [
        {
          value: '1',
          label: '未开始'
        },
        {
          value: '2',
          label: '生效中'
        },
        {
          value: '3',
          label: '已结束'
        }
      ],
      currentStatus: '',
      isCollapse: true
    }
  },
  async created() {
    await this.getList({ pageNum: 1, pageSize: 10 })
    await this.getDealerDataList({ pageNum: 1, pageSize: -1 })
  },
  watch: {
    'dialogForm.amount': function (newValue, oldValue) {
      if (this.dialogForm.amount !== 0) {
        this.dialogForm.rate = 0
      }
    },
    'dialogForm.rate': function (newValue, oldValue) {
      if (this.dialogForm.rate !== 0) {
        this.dialogForm.amount = 0
      }
    }
  },
  methods: {
    handleClose(){
      this.showHistory = true
    },
    // //押金
    // amountFn(e) {
    //   if (this.dialogForm.rate != 0 || this.dialogForm.rate != "") {
    //     this.$message.warning("已选押金比例,如需选择定额押金,请把押金比例归零");
    //   }
    // },
    // rateFn(e) {
    //   if (this.dialogForm.amount != 0 || this.dialogForm.amount != "") {
    //     this.$message.warning("已选定额押金,如需选择押金比例,请把定额押金归零");
    //   }
    // },
    // 导入
    async handleImport(param) {
      const file = param.file

      const formData = new FormData()
      formData.append('file', file)

      let result = await handleImport('customer/deposit/import', formData)

      console.log(result)
      this.importFileList = []
      if (result.code == 200) {
        this.$message.success('导入成功')
      } else {
        this.$message.error(result.message)
      }
    },
    //下载模板
    async downLoadFn() {
      downloadFiles('customer/deposit/downModel')
    },
    //记录
    logFn(id) {
      this.historyId = id
      this.showHistory = false
    },
    //取消
    async cancelFn() {
      this.dialogForm = {
        amount: 0,
        customerId: '',
        customerName: '',
        customerNumber: '',
        endTime: '',

        rate: 0,
        remark: '',
        startTime: ''
      }
      await this.$refs.dialogForm.resetFields()
      this.showDialog = false
    },
    //编辑
    async editFn(id) {
      console.log(id)
      this.title = '经销商工程机押金比例设置'
      const res = await infoDealerDeposit({ id })
      this.dialogForm = res.data
      this.dialogForm.rate = parseInt(res.data.rate * 100)
      this.showDialog = true
    },
    //删除
    async deleFn(id) {
      await deleDealerDeposit({ id })
      this.$message.success('删除成功')
      this.getList({ pageNum: 1, pageSize: 10 })
    },
    //获取经销商数据
    async getDealerDataList(data) {
      const res = await getDealerList(data)
      this.dealerList = res.data.records
    },

    // 更改每页数量
    handleSizeChange(val) {
      this.pageSize = val

      this.getList({
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.searchForm.customerName,
        currentStatus: this.searchForm.currentStatus
      })
    },
    // 更改当前页
    handleCurrentChange(val) {
      this.currentPage = val
      this.getList({
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.searchForm.customerName,
        currentStatus: this.searchForm.currentStatus
      })
    },
    //搜索功能
    async searchFn() {
      console.log(this.searchForm)
      await this.getList({
        keyword: this.searchForm.customerName,
        currentStatus: this.searchForm.currentStatus,
        pageNum: 1,
        pageSize: this.pageSize
      })
    },
    //重置
    clearFn() {
      console.log(this.$refs.searchForm)
      this.$refs.searchForm.resetFields()
    },
    //获取列表数据
    async getList(data) {
      const res = await getDealerDepositList(data)
      console.log(res)
      this.dataList = res.data.records
      this.listTotal = res.data.total
    },
    async addDataListFn() {
      await this.$refs.dialogForm.validate()

      // if (this.dialogForm.rate !== 0) {
      //   this.dialogForm.amount = 0;
      // }
      // if (this.dialogForm.amount !== 0) {
      //   this.dialogForm.rate = 0;
      // }

      let res = this.dealerList.filter(v => v.id === this.dialogForm.customerId)[0]

      this.dialogForm.customerName = res.name
      this.dialogForm.customerNumber = res.number

      if (!this.dialogForm.endTime) {
        this.dialogForm.endTime = '2100-01-01 00:00:00'
      }
      if (this.dialogForm.id) {
        await editDealerDeposit({
          ...this.dialogForm,
          rate: this.dialogForm.rate / 100
        })
        this.$message.success('编辑成功')
      } else {
        await getDealerDepositAdd({
          ...this.dialogForm,
          rate: Number(this.dialogForm.rate / 100),
          amount: Number(this.dialogForm.amount)
        })
        this.$message.success('添加成功')
      }
      this.dialogForm = {
        amount: 0,
        customerId: '',
        customerName: '',
        customerNumber: '',
        endTime: '',

        rate: 0,
        remark: '',
        startTime: ''
      }

      this.getList({ pageNum: 1, pageSize: 10 })
      this.showDialog = false
    },
    addFn() {
      this.title = '经销商工程机押金比例设置'
      this.showDialog = true
    }
  }
}
</script>

<style lang="scss" scoped>
.selectStyle {
  width: 100%;
}
::v-deep .el-textarea__inner {
  resize: none;
}
::v-deep .el-form {
  .inputStyle {
    width: 80%;
  }
}
::v-deep .dialog-footer {
  display: flex;
  justify-content: center;
}
::v-deep .el-dialog__header {
  background-color: #dddddd;
}
.inp {
  margin: 0 12px;
}

.right {
  margin-top: 12px;
  float: right;
}

.table {
  margin-top: 12px;
}
.search {
  display: flex;
  margin-top: 12px;
  ::v-deep .el-input {
    width: 50%;
    margin-right: 12px;
  }
}
.import-btn {
  display: inline-block;
  margin-left: 10px;
}
// .main {
//   padding: 12px;
// }
</style>

