<template>
  <base-list class="addedit-rule">
    <template slot="n_header">
      <el-form v-model="pagerDto" inline />
    </template>
    <template slot="n_option">
      <el-button type="primary" size="small" icon="el-icon-plus" @click="hanleAddEditRule()">
        新增规则
      </el-button>
    </template>
    <template>
      <vxe-table
        border
        show-overflow
        :data="dataSource"
        :loading="tableLoading"
        :row-config="{isHover: true}"
        :header-row-style="{
          background: '#E6F7FF',
          borderRight: '1px solid #ccc',
        }"
        :column-config="{ resizable: true }"
      >
        <vxe-column field="ChannelId" title="渠道名称" :min-width="160">
          <template #default="{ row }">
            {{ row.ChannelId | getChannelIdName(channels) }}
          </template>
        </vxe-column>
        <vxe-column field="StartWeight" title="开始重量" :min-width="110" />
        <vxe-column field="EndWeight" title="结束重量" :min-width="110" />
        <vxe-column field="BL" title="占比" :min-width="90" />
        <vxe-column field="AdjStartWeight" title="上传随机开始重量" :min-width="140" />
        <vxe-column field="AdjEndWeight" title="上传随机结束重量" :min-width="140" />
        <vxe-column field="CreateTime" title="添加时间" :min-width="140">
          <template #default="{ row }">
            {{ row.CreateTime | getParseTime }}
          </template>
        </vxe-column>
        <vxe-column field="UpdateTime" title="更新时间" :min-width="140">
          <template #default="{ row }">
            {{ row.UpdateTime | getParseTime }}
          </template>
        </vxe-column>
        <!-- <vxe-column field="Adj" title="已修改订单明细" :min-width="140" /> -->
        <vxe-column field="Adj" title="操作" :width="210" fixed="right">
          <template #default="{ row }">
            <el-dropdown :hide-on-click="false" placement="bottom">
              <el-button type="primary" size="mini" icon="el-icon-arrow-down">
                操作按钮
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                  <el-button
                    type="primary"
                    size="mini"
                    icon="el-icon-edit"
                    style="width: 100%;"
                    @click="hanleAddEditRule(row)"
                    >修改</el-button>
                </el-dropdown-item>
                <el-dropdown-item style="margin: 4px 0;">
                  <el-button
                  type="info"
                  plain
                  size="mini"
                  icon="el-icon-tickets"
                  style="width: 100%;"
                  @click="hanleViewLogs(row.Id)"
                  >查看日志</el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button
                  type="success"
                  size="mini"
                  icon="el-icon-download"
                  style="width: 100%;"
                  @click="hanleDownloadOrder(row)"
                  >详细订单下载</el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="deleteRule(row.Id)"
              style="margin-left: 10px;"
            >删除</el-button>
          </template>
        </vxe-column>
      </vxe-table>
      <el-pagination
        :page-sizes="[20, 50, 100, 150, 200]"
        :current-page="pagerDto.PageIndex"
        :page-size="pagerDto.PageSize"
        background
        layout="prev, pager, next ,total ,jumper,sizes,slot "
        :total="pagerDto.total"
        @current-change="pagerSerach"
        @size-change="sizeChange"
      />
      <!-- 新增或修改规则 -->
      <el-dialog
        :title="getAddEditRuleTitle"
        :visible.sync="dialogAddEditRule"
        width="42%"
        :before-close="handleCloseAddEditRule"
        custom-class="addEditRule-form"
      >
        <el-form
          inline
          ref="addEditRuleRef"
          :model="addEditRuleParamsDto"
          :rules="AddEditRule"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="渠道名称" prop="ChannelId">
                <el-select
                  v-model="addEditRuleParamsDto.ChannelId"
                  placeholder="渠道名称"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="item in channels"
                    :key="item.Id"
                    :label="item.Name"
                    :value="item.Id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开始重量" prop="StartWeight">
                <el-input v-model="addEditRuleParamsDto.StartWeight" v-decimal-input clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束重量" prop="EndWeight">
                <el-input v-model="addEditRuleParamsDto.EndWeight" v-decimal-input clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="占比" prop="BL">
                <el-input v-model="addEditRuleParamsDto.BL" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="上传随机开始重量" prop="AdjStartWeight">
                <el-input v-model="addEditRuleParamsDto.AdjStartWeight" v-decimal-input clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="上传随机结束重量" prop="AdjEndWeight">
                <el-input v-model="addEditRuleParamsDto.AdjEndWeight" v-decimal-input clearable />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleCloseAddEditRule">取 消</el-button>
          <el-button type="primary" @click="hanleSubmitTemplate" :loading="submitTemplateLoading">保 存</el-button>
        </span>
      </el-dialog>
      <!-- 日志 -->
      <el-dialog
        title="日志"
        width="58%"
        :visible.sync="dialogLogs"
      >
        <vxe-table
          border
          height="600px"
          show-overflow
          :data="logsSource"
          :row-config="{isHover: true}"
          :header-row-style="{
            background: '#E6F7FF',
            borderRight: '1px solid #ccc',
          }"
          :column-config="{ resizable: true }"
        >
          <vxe-column title="创建时间" field="CreateTime" :min-width="160" />
          <vxe-column title="创建用户" field="CreateUserName" :min-width="110" />
          <vxe-column title="操作描述" field="FieldDesc" :min-width="110" />
          <vxe-column title="操作旧内容" field="OldValue" :min-width="110" />
          <vxe-column title="操作新内容" field="NewValue" :min-width="110" />
        </vxe-table>
      </el-dialog>
    </template>
  </base-list>
</template>

<script>
import BaseList from '@/components/Xyy/baselist'
import {
  _getServiceWeiAdjPageResult,
  _updateServiceWeiAdj,
  _addServiceWeiAdj,
  _deleteServiceWeiAdj,
  _getServiceWeiAdjChangeLogs,
  _getServiceWeiAdjChangeDetails
} from '@/api/channel/providerWeightAdj'
import { _getDeliverChannel } from '@/api/baseInfo'
import { getFormattedDateTime } from '@/utils'
import { exportExcel } from '@/utils/filedown'

export default{
  name: 'ProviderWeightAdj',
  components: { 'base-list': BaseList },
  // vue指令
  directives: {
    decimalInput: {
      bind: function(el, binding, vnode) {
        el.handleInput = function handleInput(event) {
          const input = event.target
          const value = input.value
          // 移除非数字字符和超过两位小数的部分
          const newValue = value.replace(/[^0-9.]/g, '').replace(/^\D*(\d*(?:\.\d{0,3})?).*$/g, '$1')
          input.value = newValue
          // 更新双向绑定
          vnode.componentInstance.$emit('input', newValue)
        }
        el.addEventListener('input', el.handleInput)
      },
      unbind(el) {
        el.removeEventListener('input', el.handleInput)
      }
    }
  },
  data() {
    return {
      pagerDto: {
        PageIndex: 1,
        PageSize: 20,
        total: 0
      },
      dataSource: [],
      dialogAddEditRule: false,
      isAddEditRule: true,
      addEditRuleParamsDto: {
        ChannelId: undefined,
        StartWeight: undefined,
        EndWeight: undefined,
        BL: undefined,
        AdjStartWeight: undefined,
        AdjEndWeight: undefined,
        Id: undefined,
      },
      AddEditRule: {
        ChannelId: [{ required: true, message: '请选择渠道名称', trigger: 'change' }],
        StartWeight: [{ required: true, message: '请输入开始重量', trigger: 'blur' }],
        EndWeight: [{ required: true, message: '请输入结束重量', trigger: 'blur' }],
        BL: [{ required: true, message: '请输入占比', trigger: 'blur' }],
        AdjStartWeight: [{ required: true, message: '请输入上传随机开始重量', trigger: 'blur' }],
        AdjEndWeight: [{ required: true, message: '请输入上传随机结束重量', trigger: 'blur' }],
      },
      tableLoading: false,
      channels: [],
      // 日志
      dialogLogs: false,
      logsSource: [],
      submitTemplateLoading: false
    }
  },
  computed: {
    getAddEditRuleTitle() {
      return this.isAddEditRule ? '新增规则' : '编辑规则'
    }
  },
  filters: {
    getChannelIdName(val, list) {
      if(!val) return ''
      const findObj = list.find((item) => item.Id === val)
      return findObj?.Name
    },
    getParseTime(timerStr) {
      return getFormattedDateTime(timerStr)
    }
  },
  created() {
    this.serarch()
    _getDeliverChannel().then((response) => {
      this.channels = response
    })
  },
  methods: {
    // 删除
    deleteRule(Id) {
      _deleteServiceWeiAdj(Id).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.serarch()
      })
    },
    // 添加及编辑
    // 新增、修改
    hanleSubmitTemplate() {
      if(this.isAddEditRule) {
        this.$refs.addEditRuleRef.validate((valid) => {
          if (valid) {
            this.submitTemplateLoading = true
            _addServiceWeiAdj(this.addEditRuleParamsDto).then(() => {
              this.$message({
                type: 'success',
                message: '新增成功!'
              })
              this.serarch()
              this.dialogAddEditRule = false
            }).finally(() => {
              this.submitTemplateLoading = false
            })
          } else {
            return false
          }
        })
      } else {
        this.$refs.addEditRuleRef.validate((valid) => {
          if (valid) {
            this.submitTemplateLoading = true
            _updateServiceWeiAdj(this.addEditRuleParamsDto).then(() => {
              this.$message({
                type: 'success',
                message: '编辑成功!'
              })
              this.serarch()
              this.dialogAddEditRule = false
            }).finally(() => {
              this.submitTemplateLoading = false
            })
          } else {
            return false
          }
        })
      }
    },
    hanleAddEditRule(data) {
      this.isAddEditRule = true
      this.addEditRuleParamsDto.Id = undefined
      if (data) {
        this.isAddEditRule = false
        Object.keys(data).forEach((key) => {
          this.addEditRuleParamsDto[key] = data[key]
        })
      }
      this.$nextTick(() => {
        this.dialogAddEditRule = true
      })
    },
    handleCloseAddEditRule() {
      this.$refs.addEditRuleRef.resetFields()
      this.dialogAddEditRule = false
    },
    // 查询
    pagerSerach(page) {
      this.pagerDto.PageIndex = page
      this.serarch()
    },
    sizeChange(pageSize) {
      this.pagerDto.PageIndex = 1
      this.pagerDto.PageSize = pageSize
      this.serarch()
    },
    serarch() {
      this.tableLoading = true
      _getServiceWeiAdjPageResult(this.pagerDto)
        .then((response) => {
          this.dataSource = response.Result
          this.pagerDto.total = response.TotalCount
        })
        .finally((response) => {
          this.tableLoading = false
        })
    },
    // 查看操作日志
    hanleViewLogs(Id) {
      _getServiceWeiAdjChangeLogs(Id).then(r => { this.logsSource = r; this.dialogLogs = true })
    },
    // 详细订单下载
    hanleDownloadOrder(row) {
      const findObj = this.channels.find((item) => item.Id === row.ChannelId)
      exportExcel('/ServiceWeiAdj/GetChangeDetails?id=' + row.Id, {}, "get", `${findObj?.Name} ${row.StartWeight}-${row.EndWeight}`)
    }
  }
}
</script>
<style>
.addedit-rule .row--hover {
  background-color: #E6F7FF !important;
}
.addEditRule-form .el-form-item {
  width: 92%;
}
.addEditRule-form .el-form-item__label {
  text-align: left;
  line-height: 32px;
}

.addEditRule-form .el-form-item__content,
.addEditRule-form .el-select {
  width: 100%;
}

@media screen and (max-width: 1240px) {
  .addEditRule-form .el-col-12,
  .addEditRule-form .el-form-item {
    width: 100%;
  }
}
</style>
