<template>
  <div class="sysseting-container">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="基本信息" name="base">
        <el-form :model="baseForm" label-width="120px" class="tab-form">
          <el-form-item label="投诉电话">
            <el-input v-model="baseForm.phone" placeholder="请输入投诉电话" style="width: 300px" />
          </el-form-item>
          <el-form-item label="抢单开始时间">
            <el-time-picker v-model="baseForm.startTime" placeholder="选择时间" format="HH:mm" value-format="HH:mm" style="width: 150px" />
          </el-form-item>
          <el-form-item label="抢单结束时间">
            <el-time-picker v-model="baseForm.endTime" placeholder="选择时间" format="HH:mm" value-format="HH:mm" style="width: 150px" />
          </el-form-item>
          <el-form-item label="质保金扣除比例">
            <el-input-number v-model="baseForm.marginRate" :min="0" :max="100" />
            <span style="margin-left: 8px">%</span>
          </el-form-item>
          <el-form-item label="下单送积分">
            <el-input v-model="baseForm.orderScore" style="width: 120px" />
            <el-tooltip content="下单支付金额多少元赠送1积分，不填则不赠送" placement="right">
              <i class="el-icon-question" style="margin-left: 8px; color: #999" />
            </el-tooltip>
          </el-form-item>
          <el-form-item label="搜索热词">
            <el-select v-model="baseForm.hotwords" multiple filterable allow-create default-first-option placeholder="请输入热词" style="width: 600px">
              <el-option v-for="item in baseForm.hotwords" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item label="客服二维码">
            <el-upload
              class="avatar-uploader"
              action="#"
              :show-file-list="false"
              :on-change="handleQrChange"
              :before-upload="beforeQrUpload"
            >
              <img v-if="baseForm.qrUrl" :src="baseForm.qrUrl" class="qr-img" />
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveAllConfig('1')">提交</el-button>
            <el-button @click="resetBase">重置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="文本配置" name="text">
        <el-form :model="textForm" label-width="120px" class="tab-form">
          <el-form-item label="公司名称">
            <el-input v-model="textForm.company" placeholder="请输入公司名称" />
          </el-form-item>
          <el-form-item label="简介">
            <el-input type="textarea" v-model="textForm.intro" :rows="4" placeholder="请输入公司简介" />
          </el-form-item>
          <el-form-item label="质保金说明">
            <quill-editor v-model="textForm.marginDesc" :options="editorOptions" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveAllConfig('2')">提交</el-button>
            <el-button @click="resetText">重置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="下单时间配置" name="orderTime">
        <el-form label-width="120px" class="tab-form">
          <el-form-item label="下单时间">
            <div v-for="(item, idx) in orderTimes" :key="idx" style="display: flex; align-items: center; margin-bottom: 8px;">
              <el-time-picker
                v-model="item.start"
                placeholder="开始时间"
                format="HH:mm"
                value-format="HH:mm"
                style="width: 130px; margin-right: 8px;"
                @change="updateTimeRange(idx)"
              />
              <span style="margin: 0 4px;">-</span>
              <el-time-picker
                v-model="item.end"
                placeholder="结束时间"
                format="HH:mm"
                value-format="HH:mm"
                style="width: 130px; margin-right: 12px;"
                @change="updateTimeRange(idx)"
              />
              <el-input-number v-model="item.count" :min="0" style="width:25%; margin-right: 12px;" />
              <el-button icon="el-icon-delete" type="danger" @click="removeOrderTime(idx)" circle />
            </div>
            <el-button type="primary" icon="el-icon-plus" @click="addOrderTime">新增</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveAllConfig('3')">提交</el-button>
            <el-button @click="resetOrderTime">重置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="时间配置" name="time">
        <el-form :model="timeForm" label-width="120px" class="tab-form">
          <el-form-item label="每月提现时间">
            <el-select v-model="timeForm.withdrawDays" multiple placeholder="请选择日期" style="width: 300px">
              <el-option v-for="d in 31" :key="d" :label="d + '号'" :value="d + '号'" />
            </el-select>
          </el-form-item>
          <el-form-item label="定时接单时长">
            <el-input-number v-model="timeForm.autoOrderMinutes" :min="1" style="width: 120px" />
            <span style="margin-left: 8px">分钟</span>
            <div class="el-form-item__tip">订单无人接单时多少分钟后，自动重新派单。单位（分钟）</div>
          </el-form-item>
          <el-form-item label="取消订单时长">
            <el-input-number v-model="timeForm.cancelOrderDays" :min="1" style="width: 120px" />
            <span style="margin-left: 8px">天</span>
            <div class="el-form-item__tip">师傅到达之后，多久之后没有报工则取消订单。单位（天）</div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveAllConfig('4')">提交</el-button>
            <el-button @click="resetTime">重置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <el-button type="primary" style="margin-top: 24px;" @click="saveAllConfig">保存全部配置</el-button>
  </div>
</template>

<script>
import { listSiteConfig, getSiteConfig, delSiteConfig, addSiteConfig, updateSiteConfig } from "@/api/system/SiteConfig"
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

export default {
  name: 'SysSeting',
  components: {
    quillEditor
  },
  data() {
    return {
       // 遮罩层
      loading: true,
      activeTab: 'base',
      SiteConfigList: [],
      config_one: {},   
      config_two: {},
      config_three: {},
      config_four: {},
      total: 0,   // 系统配置表格数据
      // 基本信息
      baseForm: {
        phone: '',
        startTime: '',
        endTime: '',
        marginRate: 10,
        orderScore: 100,
        hotwords: ['水电维修', '家电清洗', '灯具维修', '墙面翻新', '门窗家具', '疏通维修', '防水维修'],
        qrUrl: ''
      },
      // 文本配置
      textForm: {
        company: '',
        intro: '',
        marginDesc: ''
      },
     
      // 下单时间配置
      orderTimes: [
        
      ],
      // 时间配置
      timeForm: {
        withdrawDays: ['8号', '18号', '28号'],
        autoOrderMinutes: 10,
        cancelOrderDays: 7
      },
      editorOptions: {
        placeholder: '请输入质保金说明...'
      }
    }
  },
  created() {
         this.getList()
      },
  methods: {
     /** 查询系统配置列表 */
     getList() {
      this.loading = true
      listSiteConfig(this.queryParams).then(response => {
        this.SiteConfigList = response.rows

        // config_one 基本信息
        this.config_one=response.rows.find(item => item.name === 'config_one')
        const configOneObj =JSON.parse(this.config_one.value) 

     
        if (configOneObj) {
          this.baseForm = {
            phone: configOneObj.phone || '',
            startTime:configOneObj.loot_start || '',
            endTime: configOneObj.loot_end || '',
            marginRate: configOneObj.margin || 10,
            orderScore: configOneObj.orderScore || 100,
            hotwords: configOneObj.hot || [],
            qrUrl: configOneObj.kf || '',
          }
        }

        // config_two 文本配置
        this.config_two=response.rows.find(item => item.name === 'config_two')
        const configTwoObj =JSON.parse(this.config_two.value) 

        if (configTwoObj) {
          this.textForm = {
            company: configTwoObj.name || '',
            intro: configTwoObj.brief || '',
            marginDesc: configTwoObj.money_explain || ''
          }
        }

        // config_three 下单时间配置
        this.config_three=response.rows.find(item => item.name === 'config_three')
      
        let _data=JSON.parse(this.config_three.value)
        for(let key in _data.time){
          const [start, end] =_data.time[key].key.split('-');
          this.orderTimes.push({
            start: start || '',
            end: end || '',
            count: _data.time[key].num || 99
          })
        }
      
  
       

        // config_four 时间配置
        this.config_four=response.rows.find(item => item.name === 'config_four')
        const configFourObj =JSON.parse(this.config_four.value) 

        if (configFourObj) {
          this.timeForm = {
            withdrawDays: configFourObj.time || [],
            autoOrderMinutes: configFourObj.order_time || 10,
            cancelOrderDays: configFourObj.remove_time || 7
          }
        }

        this.total = response.total
        this.loading = false
      })
    },
    // 基本信息
    submitBase() {
      this.$message.success('提交成功（模拟）')
    },
    resetBase() {
      this.$refs.baseForm && this.$refs.baseForm.resetFields && this.$refs.baseForm.resetFields()
    },
    handleQrChange(file) {
      // 模拟上传二维码
      const reader = new FileReader()
      reader.onload = e => {
        this.baseForm.qrUrl = e.target.result
      }
      reader.readAsDataURL(file.raw)
    },
    beforeQrUpload(file) {
      const isImg = file.type.startsWith('image/')
      if (!isImg) {
        this.$message.error('只能上传图片格式')
      }
      return isImg
    },
    // 文本配置
    submitText() {
      this.$message.success('提交成功（模拟）')
    },
    resetText() {
      this.textForm = { company: '', intro: '', marginDesc: '' }
    },
    // 下单时间配置
    updateTimeRange(idx) {
      const item = this.orderTimes[idx];
      if (item.start && item.end && item.start >= item.end) {
        this.$message.error('结束时间必须大于开始时间');
        item.end = '';
      }
    },
    addOrderTime() {
      this.orderTimes.push({ start: '', end: '', count: 99 });
    },
    removeOrderTime(idx) {
      this.orderTimes.splice(idx, 1)
    },
    submitOrderTime() {
      // 提交时拼接时间段
      const timeList = this.orderTimes.map(item => ({
        time: `${item.start}-${item.end}`,
        count: item.count
      }));
      // 这里可以将 timeList 发送给后端
      this.$message.success('提交成功（模拟）')
    },
    resetOrderTime() {
      this.orderTimes = [
      
      ]
    },
    // 时间配置
    submitTime() {
      this.$message.success('提交成功（模拟）')
    },
    resetTime() {
      this.timeForm = { withdrawDays: ['8号', '18号', '28号'], autoOrderMinutes: 10, cancelOrderDays: 7 }
    },
    async saveAllConfig(e) {
      // 1. 组装 config_one
      const config_one = {
        phone: this.baseForm.phone,
        loot_start: this.baseForm.startTime,
        loot_end: this.baseForm.endTime,
        margin: this.baseForm.marginRate,
        orderScore: this.baseForm.orderScore,
        hot: this.baseForm.hotwords,
        kf: this.baseForm.qrUrl
      };
      // 2. 组装 config_two
      const config_two = {
        name: this.textForm.company,
        brief: this.textForm.intro,
        money_explain: this.textForm.marginDesc
      };
      // 3. 组装 config_three
      const config_three = {
        time: this.orderTimes.map(item => ({
          key: `${item.start}-${item.end}`,
          num: item.count
        }))
      };
      // 4. 组装 config_four
      const config_four = {
        time: this.timeForm.withdrawDays,
        order_time: this.timeForm.autoOrderMinutes,
        remove_time: this.timeForm.cancelOrderDays
      };
      try {
if(e=='1'){
        await updateSiteConfig({ name: 'config_one',id:this.config_one.id, value: JSON.stringify(config_one) });
}else if(e=='2'){
        await updateSiteConfig({ name: 'config_two',id:this.config_two.id, value: JSON.stringify(config_two) });
}else if(e=='3'){
        await updateSiteConfig({ name: 'config_three',id:this.config_three.id, value: JSON.stringify(config_three) });
}else if(e=='4'){
          await updateSiteConfig({ name: 'config_four',id:this.config_four.id, value: JSON.stringify(config_four) });
}
        this.$message.success('保存成功！');
        this.getList();
      } catch (e) {
        this.$message.error('保存失败，请重试');
      }
    }
  }
}
</script>

<style scoped>
.sysseting-container {
  background: #fff;
  padding: 24px;
  min-height: 600px;
}
.tab-form {
  max-width: 900px;
}
.qr-img {
  width: 120px;
  height: 120px;
  border: 1px solid #eee;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 120px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.avatar-uploader-icon {
  font-size: 32px;
  color: #8c939d;
}
</style>
