<template>
  <a-form
    :model="form"
    :label-col="{sm: { span: 8 } }"
    :wrapper-col="{ span:24}"
    ref="formRef"
  >
    <a-row :gutter="8">
      <a-col :xs="12">
        <a-form-item
          required
          name="isOperate"
          :rules="[{ required: true, message: '请选择是否运营' }]"
        >
          <template #label>
            是否运营
            <a-tooltip title="是否开通运营，是为正常运营，否为停运">
              <QuestionCircleOutlined style="margin-left: 5px;color: rgb(192,192,192);" />
            </a-tooltip>
          </template>
          <a-radio-group
            v-model:value="form.isOperate"
            name="radioGroup"
            @change="changeIsOperate"
          >
            <a-radio value="1">运营中</a-radio>
            <a-radio value="2">停止运营</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-col>
    </a-row>
    <a-row
      v-if="showStopTimeInfo"
      :gutter="8"
    >
      <a-col :xs="12">
        <a-form-item
          label="停运时间"
          required
          name="stopTimeInfo"
          :rules="[{ required: true, message: '请选择停运时间' }]"
        >
          <a-range-picker
            :show-time="{ format: 'HH:mm' }"
            valueFormat="YYYY-MM-DD HH:mm"
            v-model:value="form.stopTimeInfo"
            :placeholder="['请选择停运时间起', '请选择停运时间止']"
          />
        </a-form-item>
      </a-col>
    </a-row>
    <a-row :gutter="8">
      <a-col :xs="12">
        <a-form-item
          label="运营类型"
          required
          name="operateType"
          :rules="[{ required: true, message: '请选择运营类型' }]"
        >
          <a-radio-group
            v-model:value="form.operateType"
            name="radioGroup"
            @change="changeOperateType"
          >
            <a-radio value="1">默认</a-radio>
            <a-radio value="2">按时间运营</a-radio>
            <a-radio value="3">按周运营</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-col>
    </a-row>
    <a-row
      :gutter="8"
      v-if="showOperateTime"
    >
      <a-col
        v-if="time"
        :xs="12"
      >
        <a-form-item
          required
          label="运营时间"
          name="operateTimeBytime"
          :label-col="{ sm: { span: 8 }}"
          :wrapper-Col="{span: 24 }"
          :rules="[{ required: true, message: '请添加运营时间' }]"
        >
          <TimeRangePicker
            v-model:value="form.operateTimeBytime"
          />
        </a-form-item>
      </a-col>
      <a-col
        v-if="week"
        :xs="24"
      >
        <a-form-item
          required
          label="运营时间"
          name="operateTimeByWeek"
          :label-col="{ sm: { span: 4 }}"
          :wrapper-Col="{span: 24 }"
          :rules="[{ required: true, message: '请添加运营时间' }]"
        >
          <a-table
            bordered
            :columns="columns"
            :dataSource="form.operateTimeByWeek"
            :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>
              <div id="timePicker"></div>
              <template v-if=" column.type == 'time'">
                <TimeRangePicker
                  v-model:value="record[column.dataIndex]"
                />
              </template>
              <template v-if=" column.type == 'select'">
                <a-tooltip
                  color="white"
                  :open="true"
                  :getPopupContainer="getPopupContainerFunc"
                  v-if="record['toolTip']"
                >
                  <template #title>
                    <div style="color: red;">已选择相同的周天数！</div>
                  </template>
                  <a-select
                    v-model:value="record[column.dataIndex]"
                    mode="multiple"
                    style="width: 100%"
                    placeholder="请选择"
                    :max-tag-count="1"
                    @change="checkWeek"
                  >
                    <a-select-option value="1">周一</a-select-option>
                    <a-select-option value="2">周二</a-select-option>
                    <a-select-option value="3">周三</a-select-option>
                    <a-select-option value="4">周四</a-select-option>
                    <a-select-option value="5">周五</a-select-option>
                    <a-select-option value="6">周六</a-select-option>
                    <a-select-option value="7">周日</a-select-option>
                  </a-select>
                </a-tooltip>
                <a-select
                  v-else
                  v-model:value="record[column.dataIndex]"
                  mode="multiple"
                  style="width: 100%"
                  placeholder="请选择"
                  :max-tag-count="1"
                  @change="checkWeek"
                >
                  <a-select-option value="1">周一</a-select-option>
                  <a-select-option value="2">周二</a-select-option>
                  <a-select-option value="3">周三</a-select-option>
                  <a-select-option value="4">周四</a-select-option>
                  <a-select-option value="5">周五</a-select-option>
                  <a-select-option value="6">周六</a-select-option>
                  <a-select-option value="7">周日</a-select-option>
                </a-select>
              </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-row
      :gutter="8"
      v-if="stopInfoFlag"
    >
      <a-col :xs="24">
        <a-form-item
          label="停运公告"
          name="stopInfo"
          :label-col="{ sm: { span: 4 }}"
          :wrapper-Col="{span: 12 }"
        >
          <a-textarea
            v-model:value="form.stopInfo"
            placeholder="请输入停运公告"
            :rows="4"
          />
        </a-form-item>
      </a-col>
    </a-row>
    <a-row
      v-if="!showStopTimeInfo"
      :gutter="8"
    >
      <a-col :xs="12">
        <a-form-item
          required
          name="channel"
          :rules="[{ required: true, message: '请选择访问渠道' }]"
        >
          <template #label>
            访问渠道
            <a-tooltip title="单独配置支付宝和微信小程序是否可以用车">
              <QuestionCircleOutlined style="margin-left: 5px;color: rgb(192,192,192);" />
            </a-tooltip>
          </template>
          <a-checkbox-group
            v-model:value="form.channel"
            name="channel"
            :options="[ 
                { label: '微信', value: '1' },
                { label: '支付宝', value: '2' }]"
          />
        </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 stopInfoFlag = ref(false);
const formRef = ref();
const time = ref(false);
const week = ref(false);
const showOperateTime = ref(false);
const form = ref({
  operateTimeByWeek: [],
  operateTimeBytime: null,
  tableName: 'ebikeSysRoperatesetDto'
});
const showStopTimeInfo = ref(false);
const saveFlag = ref(true);
const openWeekTip = ref(false)

const columns = ref([
  {
    title: '周',
    key: 'weekday',
    width: 150,
    align: 'center',
    dataIndex: 'weekday',
    type: "select"
  },
  {
    title: '工作时间',
    key: 'workTime',
    width: 300,
    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.operateTimeByWeek.push({
        key: res.data,
        weekday: [],
        workTime: []
      })
    }
  })
}

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

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

const getPopupContainerFunc = () => {
  return document.getElementById("timePicker");
}

const changeIsOperate = (e) => {
  const value = e.target.value;
  if (value == '2') {
    showStopTimeInfo.value = true
    showOperateTime.value = true;
    stopInfoFlag.value = true;
  } else {
    showStopTimeInfo.value = false
    showOperateTime.value = false;
    stopInfoFlag.value = false;
    form.value.stopTimeInfo = null;
    form.value.operateType = null;
  }
}

const changeOperateType = (data) => {
  const value = data.target.value;
  if (value == "2") {
    showOperateTime.value = true;
    time.value = true;
    week.value = false;
  } else if (value == "3") {
    showOperateTime.value = true;
    week.value = true;
    time.value = false;
  } else {
    week.value = false;
    time.value = false;
    showOperateTime.value = false;
    form.value.operateTimeBytime = null;
    form.value.operateTimeByWeek = [];
    if (form.value.isOperate == '1') {
      stopInfoFlag.value = false
    }
  }
}

const checkWeek = () => {
  openWeekTip.value = false;
  saveFlag.value = true;
  const seenWeeks = [];
  form.value['operateTimeByWeek'].forEach(items => {
    const week = items['weekday'];
    items['toolTip'] = false;
    if (week.some(item => seenWeeks.includes(item))) {
      openWeekTip.value = true;
      items['toolTip'] = true;
      saveFlag.value = false;
    } else {
      seenWeeks.push(...week);
    }
  });
}

const validateForm = async () => {

  await formRef.value.validate();
  const formData = _.cloneDeep(formRef.value.getFieldsValue());
  if (formData['isOperate'] == '2') {
    formData['stopStartTime'] = dayjs(formData['stopTimeInfo'][0]).format('YYYY-MM-DD HH:mm'),
      formData['stopEndTime'] = dayjs(formData['stopTimeInfo'][1]).format('YYYY-MM-DD HH:mm')
  }
  if (formData['operateType'] == '2') {
    formData['operateTime'] = [{
      startWorktime: dayjs(formData['operateTimeBytime'][0]).format('HH:mm:ss'),
      endWorktime: dayjs(formData['operateTimeBytime'][1]).format('HH:mm:ss')
    }]
  } else if (formData['operateType'] == '3') {
    formData['operateTime'] = [];
    formData['operateTimeByWeek'].map(item => {
      formData['operateTime'].push({
        weekday: item['weekday'],
        startWorktime: dayjs(item['workTime'][0]).format('HH:mm:ss'),
        endWorktime: dayjs(item['workTime'][1]).format('HH:mm:ss'),
      })
    })
  } else {
    formData['operateTime'] = [];
  }
  formData['tableName'] = form.value.tableName
  formData['id'] = form.value.id
  delete formData['operateTimeBytime'];
  delete formData['operateTimeByWeek'];
  delete formData['stopTimeInfo'];
  return formData;
}

const loadFormData = (formData) => {
  if (formData) {
    if (formData['isOperate'] == '2') {
      formData['stopTimeInfo'] = [dayjs(formData['stopTimeInfo'][0], 'YYYY-MM-DD HH:mm'),
      dayjs(formData['stopTimeInfo'][0], 'YYYY-MM-DD HH:mm')]
      delete formData['stopStartTime']
      delete formData['stopEndTime']
    }
    if (formData['operateType'] == "2") {
      formData['operateTimeBytime'].map(item => {
        item['operateTimeBytime'] = [dayjs(item['startWorktime'], 'HH:mm:ss'), dayjs(item['endWorktime'], 'HH:mm:ss')]
        delete item['startWorktime'];
        delete item['endWorktime'];
      })
    } else if (formData['operateType'] == "3") {
      formData['operateTimeByWeek'].map(item => {
        item['workTime'] = [dayjs(item['startWorktime'], 'HH:mm:ss'), dayjs(item['endWorktime'], 'HH:mm:ss')]
        delete item['startWorktime'];
        delete item['endWorktime'];
      })
    }
    form.value = { ...form.value, ...formData }
    if (formData['isOperate'] == '2') {
      changeIsOperate({ target: { value: formData['isOperate'] } })
    }
    if (formData['operateType']) {
      changeOperateType({ target: { value: formData['operateType'] } })
    }
  } else {
    callOperate("/ebikesysrcostset/createSnowflakeId", {}, "get").then(res => {
      if (res.code == 200) {
        form.value['id'] = res.data;
      }
    })
  }
}

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

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

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