<template>
  <div style="display: flex" v-bind="$attrs">
    <!-- {{ $attrs.value }} -->
    <!-- {{simpleDayOptions}} -->
    <!-- <div v-if="columsType == 'complexTable'" style="color: red; display: block; width: 100%">
      注:服务频次对应每天、每周、每月、每年,均需要设置起止时间
    </div>
    <br /> -->
    <div v-if="columsType == 'complexTable'">
      <div v-if="columsType == 'complexTable'" style="color: red; display: block; width: 100%">
        &nbsp;&nbsp;&nbsp; 注:服务频次对应每天、每周、每月、每年,均需要设置起止时间
        <br />
        <br />
      </div>
      <a-table :columns="colums" :data-source="$attrs.value" bordered :pagination="false">
        <template
          v-for="(item, index) in colums"
          :key="index"
          #[item.dataIndex]="text, record, index"
        >
          <!-- {{ text }} -->

          <a-input
            v-if="
              item.otherConditions
                ? item.otherConditions && item.inputType == 'input'
                : item.inputType == 'input'
            "
            style="margin: -5px 0"
            :value="text.text"
            @change="(e) => handleChangeIndex(e, text.index, item.dataIndex, item)"
          />
          <div v-else-if="item.inputType == 'select'">
            <div v-if="text.record[item.otherConditions] === 3 && item.dataIndex == 'day'">
              <div style="display: inline-block">
                <a-select
                  style="margin: -5px 0"
                  :value="text.text"
                  @change="(e) => handleChangeIndex(e, text.index, item.dataIndex)"
                >
                  <a-select-option
                    v-for="(i, index) in simpleDayOptions"
                    :key="index"
                    :value="i.value"
                  >
                    {{ i.label }}
                  </a-select-option>
                </a-select>
              </div>
              <div style="display: inline-block"> 日</div>
            </div>
            <div v-else-if="text.record[item.otherConditions] === 4 && item.dataIndex == 'month'">
              <div style="display: inline-block">
                <a-select
                  style="margin: -5px 0; display: inline-block"
                  :value="text.text"
                  @change="(e) => handleChangeIndex(e, text.index, item.dataIndex)"
                >
                  <a-select-option
                    v-for="(i, index) in item.componentProps.options"
                    :key="index"
                    :value="i.value"
                  >
                    {{ i.label }}
                  </a-select-option>
                </a-select>
              </div>

              <div style="display: inline-block">月</div>
            </div>
            <div v-else-if="text.record[item.otherConditions] === 4 && item.dataIndex == 'day'">
              <div style="display: inline-block">
                <a-select
                  style="margin: -5px 0"
                  :value="text.text"
                  @change="(e) => handleChangeIndex(e, text.index, item.dataIndex)"
                >
                  <a-select-option
                    v-for="(i, index) in item.componentProps.options"
                    :key="index"
                    :value="i.value"
                  >
                    {{ i.label }}
                  </a-select-option>
                </a-select>
              </div>
              <div style="display: inline-block">日</div>
            </div>
            <div v-else-if="text.record[item.otherConditions] === 2 && item.dataIndex == 'week'">
              <a-select
                style="margin: -5px 0"
                :value="text.text"
                @change="(e) => handleChangeIndex(e, text.index, item.dataIndex)"
              >
                <a-select-option
                  v-for="(i, index) in item.componentProps.options"
                  :key="index"
                  :value="i.value"
                >
                  {{ i.label }}
                </a-select-option>
              </a-select>
            </div>
          </div>

          <!-- <a-select
          v-else-if="
            text.record[item.otherConditions] == item.otherValue && item.inputType == 'select'
          "
          style="margin: -5px 0"
          :value="text.text"
          @change="(e) => handleChangeIndex(e.target.value, index, 'name')"
        >
          <a-select-option v-for="(i, index) in item.componentProps.options" :key="index">
            {{ i.label }}
          </a-select-option>
        </a-select> -->

          <a-time-picker
            v-else-if="
              item.otherConditions
                ? item.otherConditions && item.inputType == 'date'
                : item.inputType == 'date'
            "
            style="width: 100px"
            size="small"
            :defaultValue="text.text ? moment(text.text, 'HH:mm:ss') : ''"
            @change="(val, dateStrings) => changeTime(val, dateStrings, text.index, 'startTime')"
            format="HH:mm:ss"
          />
          <template
            v-else-if="
              item.otherConditions
                ? item.otherConditions && item.inputType == 'modal'
                : item.inputType == 'modal'
            "
            >请选择</template
          >
          <template
            v-else-if="
              otherConditions
                ? otherConditions && item.inputType == 'input'
                : item.inputType == 'operation'
            "
            >删除</template
          >
          <template v-else>{{ text.text }}</template>
        </template>
      </a-table>
    </div>
    <div v-else-if="columsType == 'normalTable'">
      <!-- {{ $attrs.value }}--900099 -->

      <a-table :columns="colums" :data-source="$attrs.value" bordered :pagination="false">
        <template
          v-for="(item, index) in colums"
          :key="index"
          #[item.dataIndex]="text, record, index"
        >
          <!-- {{ item }} -->
          <a-input
            v-if="item.inputType == 'input'"
            style="margin: -5px 0"
            :value="text.text"
            @change="(e) => handleChangeIndex(e, text.index, item.dataIndex, item)"
          />
          <div v-else-if="item.inputType == 'select'">
            <a-select
              style="margin: -5px 0; display: inline-block"
              :value="text.text"
              @change="(e) => handleChangeIndex(e, text.index, item.dataIndex)"
            >
              <a-select-option
                v-for="(i, index) in item.componentProps.options"
                :key="index"
                :value="i.value"
              >
                {{ i.label }}
              </a-select-option>
            </a-select>
          </div>
          <div v-else-if="item.inputType == 'selectElse'">
            <!-- {{ item.componentProps }} -->
            <a-select
              style="margin: -5px 0; display: inline-block"
              :value="text.text"
              @change="(e) => handleChangeIndex(e, text.index, item.dataIndex, item)"
            >
              <a-select-option
                v-for="(i, index) in item.componentProps.options"
                :key="index"
                :value="i.value"
              >
                {{ i.label }}
              </a-select-option>
            </a-select>
          </div>
          <div v-else-if="item.inputType == 'selectApi'">
            <NsSelectApi
              v-bind="item.componentProps"
              :value="text.text"
              @change="(e) => handleChangeIndex(e, text.index, item.dataIndex)"
            />
          </div>
          <div v-else-if="item.inputType == 'upload'">
            <NvUpload v-bind="item.componentProps" :value="text.text" />
          </div>
          <div v-else-if="item.inputType == 'date'">
            <a-time-picker
              style="width: 100px"
              size="small"
              :value="text.text ? moment(text.text, 'HH:mm:ss') : ''"
              :defaultValue="text.text ? moment(text.text, 'HH:mm:ss') : ''"
              @change="
                (val, dateStrings) => changeTime(val, dateStrings, text.index, item.dataIndex)
              "
              format="HH:mm:ss"
          /></div>
          <template v-else-if="item.inputType == 'modal'">
            <!-- 请选择 -->
            <NsModalTable
              v-bind="{
                ...item.componentProps,
                record: text.record,
                valueP: text.text,
                dataIndex: item.dataIndex,
              }"
              @changeTable="changeTable"
              :value="text.text"
            />
          </template>
          <template v-else-if="item.inputType == 'operation'">
            <span v-for="(it, indexs) in item.componentProps.actionOptions" :key="indexs">
              <span
                :style="{ color: it.color }"
                style="margin-left: 5px"
                @click="optionA(it.value, text.record, text.index)"
                >{{ it.name }}</span
              >
            </span>
          </template>
          <template v-else>{{ text.text }}</template>
        </template>
        <template #footer="currentPageData">
          <!-- {{ currentPageData }} -->
          <span style="font-size: 22px; margin-left: 50%" @click="add(currentPageData)">+</span>
        </template>
      </a-table>
    </div>
    <div v-else>
      <a-row>
        <a-col :span="12">
          <div>未选择</div>
          <br />
          <a-row>
            <a-col :span="12">护理类别:</a-col>
            <a-col :span="12"
              ><ns-select :options="optionSlect" @change="handleChangeViewList"
            /></a-col>
          </a-row>
          <br />
          <div>
            <a-table
              :columns="viewColums"
              :data-source="careItems"
              :row-selection="rowSelection"
              :pagination="false"
              bordered
            />
          </div>
        </a-col>
        <a-col :span="12">
          <div>已选择</div>
          <!-- <br /> -->
          <div style="height: 8px"></div>
          <br />
          <br />
          <br />
          <a-table :columns="colums" :data-source="$attrs.value" :pagination="false" bordered>
            <template
              v-for="(item, index) in colums"
              :key="index"
              #[item.dataIndex]="text, record, index"
            >
              <!-- {{ text }} -->

              <a-input
                v-if="item.inputType == 'input'"
                style="margin: -5px 0"
                :value="text.text"
                @change="(e) => handleChangeIndex(e, text.index, item.dataIndex, item)"
              />

              <a-select
                v-else-if="item.inputType == 'select'"
                style="margin: -5px 0"
                :value="text.text"
                @change="(e) => handleChangeIndex(e, text.index, item.dataIndex, item)"
              >
                <a-select-option v-for="(i, index) in item.componentProps.options" :key="index">
                  {{ i.label }}
                </a-select-option>
              </a-select>
              <template v-else-if="item.inputType == 'modal'">请选择</template>
              <template v-else-if="item.inputType == 'operation'"
                ><span @click="handleDelete(text.index)" style="cursor: pointer">
                  删除
                </span></template
              >
              <template v-else>{{ text.text }}</template>
            </template>
          </a-table>
        </a-col>
      </a-row>
    </div>
  </div>
</template>
<script lang="ts">
  import moment from 'moment';
  import { defineComponent, ref, watch } from 'vue';
  import { NsMessage } from '../../message';
  import { http } from '/nerv-lib/util/http';
  import NsModalTable from './modal-table.vue';
  import NvUpload from './uplods.vue';
  export default defineComponent({
    name: 'NsEtable',
    components: {
      NsModalTable,
      NvUpload,
    },
    props: {
      colums: {
        type: Array,
      },
      viewColums: {
        type: Array,
      },
      tableData: {
        type: Array,
      },
      attribute: {
        type: String,
      },
      onchange: {
        type: Function,
      },
      columsType: {
        type: String,
      },
      getChildrenOptions: {
        type: Function,
      },
      addlist: {
        type: Object,
      },
    },
    emits: ['change', 'updata:longLat', 'validate', 'getChildrenOptions'],
    setup(props, context) {
      let data = [];
      let propsData = ref();
      let ids = ref(9);
      const dependency = ref();
      const selectElseOption = ref([]);
      const rowSelection = {
        type: 'checkbox',
        onChange: (selectedRowKeys: [], selectedRows: []) => {
          let dpData = context.attrs.value ? JSON.parse(JSON.stringify(context.attrs)) : [];
          const newData = [...dpData.value];
          selectedRows.forEach((item) => {
            newData.push({
              nursingItemUuid: item['uuid'],
              nursingItemName: item['itemName'],
              frequency: 1,
              times: 1,
            });
          });
          context.emit('change', newData);
        },
      };
      const optionSlect = [
        {
          label: '全部',
          value: 'all',
        },
        {
          label: '生活护理',
          value: 1,
        },
        {
          label: '医疗护理',
          value: 2,
        },
        {
          label: '康复护理',
          value: 3,
        },
      ];
      propsData = context.attrs.value ? JSON.parse(JSON.stringify(context.attrs.value)) : [];
      console.log(propsData, '98777');
      let simpleDayOptions = ref([]);
      for (let i = 0; i < 28; i++) {
        let item = {
          label: '' + (i + 1),
          value: i + 1,
        };
        simpleDayOptions.value.push(item);
      }

      let careItems = ref([]);
      const handleChangeViewList = (value) => {
        let api = '/api/pension/pension/objs/NursingItem';

        http
          .get(api, {
            itemType: value == 'all' ? '' : value,
            enable: true,
            pageSize: 10,
          })
          .then((res) => {
            if (res && res.success) {
              careItems.value = res.data.data;
              // NsMessage.success('操作成功');
            }
          })
          .catch(() => {
            NsMessage.error('列表获取失败');
          });
      };
      handleChangeViewList('all');

      const add = (e) => {
        console.log(props.addlist, 'opopop');
        // let data = {
        //   regionUuid: null,
        //   inspectionTime: null,
        //   personList: null,
        //   relation: null,
        //   // uuid:
        // };
        let list = JSON.parse(JSON.stringify(props.addlist));
        let data = { ...list };
        let edList = context.attrs.value ? JSON.parse(JSON.stringify(context.attrs.value)) : [];
        ids.value += 1;
        edList.push({ ...data, uuid: ids.value + 'uuid' });
        context.emit('change', edList);
        // console.log(e, JSON.parse(JSON.stringify(context.attrs.value)), 'add');
      };

      const changeTable = (item) => {
        let currentList = JSON.parse(JSON.stringify(context.attrs.value));
        currentList &&
          currentList instanceof Array &&
          currentList.length > 0 &&
          currentList.forEach((its) => {
            if (its.uuid == item.uuid) {
              its = Object.assign(its, item);
            }
          });

        context.emit('change', currentList);
      };

      // 表格列操作方法
      const optionA = (name, actionInfo, ind) => {
        let edList = context.attrs.value ? JSON.parse(JSON.stringify(context.attrs.value)) : [];

        if (name == 'delete') {
          edList.splice(ind, 1);
          // console.log(edList, 'edlist');
        } else if (name == 'copy') {
          // console.log('00000');
          ids.value += 1;
          edList.push({ ...actionInfo, uuid: ids.value + 'uuid' });
        }
        context.emit('change', edList);
      };

      const getElseOptins = (name, value, fieldName, index) => {
        console.log(name, value, fieldName, index, 'zhougg');
        let acinfo = props && props.colums && props.colums[index];
        console.log(acinfo, 'acinfo');
        let api = acinfo.componentProps.api;
        let params = {
          ...acinfo.componentProps.params,
          [name]: value,
        };
        console.log(params, 'acparams');

        // let api = '/api/pension/pension/objs/NursingItem';
        http
          .get(api, { ...params })
          .then((res) => {
            if (res && res.success) {
              console.log(acinfo.componentProps.selectElseOption, 'acinfo.componentProps');
              res.data &&
                res.data.forEach((item) => {
                  if (item.dictValue == value) {
                    let arr = [];
                    item.subList &&
                      item.subList.forEach((it) => {
                        arr.push({
                          label: it.dictName,
                          value: it.dictValue,
                        });
                      });
                    selectElseOption.value = arr;
                    console.log(item.subList, 'sublist');
                  }
                });
              // careItems.value = res.data.data;
              // NsMessage.success('操作成功');
            }
          })
          .catch(() => {
            NsMessage.error('列表获取失败');
          });
      };
      // dependency
      watch(dependency, (newValue, oldValue) => {
        console.log('old', oldValue);
        console.log('new', newValue);
      });

      return {
        data,
        simpleDayOptions,
        rowSelection,
        optionSlect,
        handleChangeViewList,
        careItems,
        add,
        changeTable,
        optionA,
        getElseOptins,
        selectElseOption,
      };
    },
    data() {
      return {
        editingKey: '',
        propsList: [],
        Month2Day: {
          1: 31,
          2: 28,
          3: 31,
          4: 30,
          5: 31,
          6: 30,
          7: 31,
          8: 31,
          9: 30,
          10: 31,
          11: 30,
          12: 31,
        },
      };
    },
    created() {
      this.propsList = this.$attrs.value ? JSON.parse(JSON.stringify(this.$attrs.value)) : [];
    },
    methods: {
      moment,
      changeTime(val, dateStrings, key, type) {
        let datapro = this.$attrs.value ? JSON.parse(JSON.stringify(this.$attrs.value)) : [];
        const newData = [...datapro];
        const target = newData.filter((item, index) => key === index)[0];
        if (type == 'startTime' && target['endTime']) {
          if (this.timeCompare(dateStrings, target['endTime'])) {
            NsMessage.error('开始时间不能大于结束时间');
          }
        } else if (type == 'endTime') {
          if (this.timeCompare(target['startTime'], dateStrings)) {
            NsMessage.error('开始时间不能大于结束时间');
          }
        }
        if (target) {
          target[type] = dateStrings;
          this.$emit('change', newData);
          // this.$emit('validate', false);
          // this.propsList = newData;
        }
      },

      timeCompare(start, end) {
        let flag = true;
        if (!start || !end) return true;
        let startH = +start.split(':')[0];
        let startM = +start.split(':')[1];
        let endH = +end.split(':')[0];
        let endM = +end.split(':')[1];
        // 开始小时大于结束小时
        if (startH > endH) {
          flag = false;
        } else if (startH == endH) {
          // 小时相等时,开始分钟大于结束分钟
          if (startM >= endM) {
            flag = false;
          }
        }
        return flag;
      },
      handleChangeIndex(value, key, type, item) {
        console.log(value, key, type, 'zhouhaha');
        let propsInfo = this.$attrs.value ? JSON.parse(JSON.stringify(this.$attrs.value)) : [];
        const newData = [...propsInfo];
        console.log(newData, 'newData');
        console.log([...this.propsList], 'newData');
        console.log(this.propsList, 'newData');
        const target = newData.filter((item, index) => key === index)[0];
        if (type == 'month') {
          this.colums &&
            this.colums.forEach((item: any) => {
              if (item.dataIndex == 'day') {
                item.componentProps.options = this.setOptions(this.Month2Day[value], 'dayOptions');
              }
            });
        }
        console.log(target, 'target');
        if (target) {
          target[type] = value;
          console.log(newData, 'newData');
          this.$emit('change', newData);
          // this.propsList = newData;
        }
        this.colums &&
          this.colums.forEach((item, index) => {
            console.log(item, item.dependency, '564');
            if (item.dependency == type) {
              // console.log('lopppp');
              this.$emit('getChildrenOptions', item.dependency, value, item.dataIndex);
              this.getElseOptins(item.dependency, value, item.dataIndex, index);
            }
          });
      },
      handleDelete(e) {
        let data = this.$attrs.value ? JSON.parse(JSON.stringify(this.$attrs.value)) : [];

        let newData = data.filter((item, index) => e !== index);
        // console.log(newData);
        this.$emit('change', newData);
      },
      setOptions(number: number, type: string) {
        let arr = [];
        for (let i = 0; i < number; i++) {
          let item = {
            label: '' + (i + 1),
            value: i + 1,
          };
          arr.push(item);
        }
        return arr;
      },
    },
  });
</script>
<style lang="less" scoped>
  input::-webkit-outer-spin-button,
  input::-webkit-inner-spin-button {
    -webkit-appearance: none;
  }
  #map-container {
    width: 600px;
    height: 400px;
  }
  .leftBox,
  .rightBox {
    flex: 1;
  }
  .inputArea {
    display: flex;
    line-height: 30px;
  }
  .inputSearch {
    .inputAdress {
      width: 300px;
      margin-right: 10px;
    }
  }
</style>