<template>
  <a-form
    :model="form"
    :label-col="{sm: { span: 8 } }"
    :wrapper-col="{ span:24}"
    ref="formRef"
  >
    <a-row :gutter="8">
      <a-col :xs="24">
        <a-form-item
          required
          name="onlineService"
          :rules="[{ required: true, message: '请选择在线客服' }]"
          :label-col="{ sm: { span: 4 }}"
          :wrapper-Col="{span: 24 }"
        >
          <template #label>
            在线客服
            <a-tooltip title="开启后用户可以24h留言咨询，需要在微信后台配置客服微信">
              <QuestionCircleOutlined style="margin-left: 5px;color: rgb(192,192,192);" />
            </a-tooltip>
          </template>
          <a-radio-group
            v-model:value="form.onlineService"
            name="radioGroup"
          >
            <a-radio value="1">开启</a-radio>
            <a-radio value="2">关闭</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-col>
    </a-row>
    <a-row :gutter="8">
      <a-col :xs="24">
        <a-form-item
          required
          name="customerServiceConfig"
          :label-col="{ sm: { span: 4 }}"
          :wrapper-Col="{span: 24 }"
          :rules="[{ required: true, message: '请添电话客服设置' }]"
        >
          <template #label>
            电话客服设置
            <a-tooltip title="设置区域客服和工作时间，工作时间之外用户无法电话联系客服">
              <QuestionCircleOutlined style="margin-left: 5px;color: rgb(192,192,192);" />
            </a-tooltip>
          </template>
          <a-table
            bordered
            :columns="columns"
            :dataSource="form.customerServiceConfig"
            :scroll="{ x: 'max-content' }"
            :pagination="false"
          >
            <template #headerCell="{ column }">
              <template v-if="column.key === 'action'">
                <SettingOutlined style="margin-right: 5px" />{{ column.title }}
              </template>
            </template>
            <template #bodyCell="{ column,record,index }">
              <template v-if="column.key === 'phase'">
                <a-space>
                  {{index + 1}}
                </a-space>
              </template>
              <template v-if="column.key === 'action'">

                <a-popconfirm
                  title="删除此行？"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="deleteRecord(record)"
                >
                  <a-space>
                    <a href="#">删除</a>
                  </a-space>
                </a-popconfirm>

              </template>
              <template v-if=" column.type == 'time'">
                <TimeRangePicker
                  valueFormat="HH:mm:ss"
                  v-model:value="record[column.dataIndex]"
                />
              </template>
              <template v-if=" column.type == 'input'">
                <a-input
                  v-model:value="record[column.dataIndex]"
                  :placeholder="`请输入`"
                  :style="{ width: '100%' }"
                />
              </template>
            </template>
          </a-table>
          <a-button
            type="default"
            @click="addRecord"
            :style="{
                    width: '100%',
                    marginTop: '5px',
                    border: '1px dashed #1890ff', 
                    backgroundColor: 'transparent',
                    color: '#1890ff'
                }"
          >
            <PlusOutlined />
            向下添加一行
          </a-button>
        </a-form-item>
      </a-col>
    </a-row>
  </a-form>
</template>

<script setup>
import { ref, defineProps } from 'vue'
import { TimeRangePicker } from 'ant-design-vue'
import _ from 'lodash'
import { callOperate } from '@/apis/call.js'
import dayjs from 'dayjs';


const formRef = ref();
const form = ref({
  customerServiceConfig: [],
  tableName: 'ebikeSysLinktelDto'
});
const columns = ref([
  {
    title: '阶段',
    key: 'phase',
    width: 80,
    align: 'center',
    dataIndex: 'phase'
  },
  {
    title: '客服电话',
    key: 'telnum',
    width: 200,
    align: 'center',
    dataIndex: 'telnum',
    type: 'input'
  },
  {
    title: '工作时间',
    key: 'workTime',
    width: 200,
    align: 'center',
    dataIndex: 'workTime',
    type: 'time'
  },
  {
    title: '操作',
    key: 'action',
    width: 80,
    align: 'center',
    fixed: 'right',
  }])

const addRecord = () => {
  callOperate("/ebikesysrcostset/createSnowflakeId", {}, "get").then(res => {
    if (res.code == 200) {
      form.value.customerServiceConfig.push({
        key: res.data,
        phase: "",
        telnum: "",
        workTime: "",
      })
    }
  })
}

const deleteRecord = (record) => {
  const key = record['key'];
  let item = _.clone(form.value.customerServiceConfig);
  remove(key, "key", item)
  form.value.customerServiceConfig = item;
}

const remove = (val, filed, array) => {
  const index = array.findIndex(obj => obj[filed] === val);
  if (index > -1) {
    array.splice(index, 1);
  }
}

const validateForm = async () => {
  await formRef.value.validate();
  const formData = _.cloneDeep(formRef.value.getFieldsValue());
  formData['customerServiceConfig'].map(item => {
    item['worktimeStart'] = dayjs(item['workTime'][0]).format('HH:mm:ss');
    item['worktimeEnd'] = dayjs(item['workTime'][1]).format('HH:mm:ss');
    delete item['workTime'];
    delete item['key'];
    delete item['phase'];
  })
  formData['tableName'] = form.value.tableName
  return formData;
}

const loadFormData = (formData) => {
  if (formData) {
    form.value = { ...form.value, ...formData }
  }
}

const getFormData = () => {
  return _.cloneDeep(form.value);
}

const resetFormValue = () => {
  formRef.value.resetFields()
}

defineExpose({ validateForm, resetFormValue, loadFormData, getFormData });
</script>
