/* *@description: *@author: hudw *@date: 2022-03-31 17:14:12 */
<template>
  <p-card class="full-card-panel" v-show="st > 0" :loading="loading" :bordered="false">
    <a-space slot="extra" v-if="st !== 1">
      <p-button type="primary" :icon="confirmLoading ? 'loading' : ''" @click="save">保存</p-button>
      <p-button @click="back">取消</p-button>
    </a-space>
    <a-space slot="title">
      <a-icon type="arrow-left" @click="back(record && record.id)" :style="{ color: '#08c' }" />
      {{ title }}
    </a-space>

    <p-grid-form ref="grid" :items="formItems" :span="6">
      <template slot="diy" slot-scope="value, form">
        <a-row :gutter="10" style="width: 800px" v-for="(item, index) in form.getFieldValue('messageConfigConditionVOList')" :key="item.id">
          <a-col :span="7">
            <p-select
              :disabled="st == 1"
              :options="selectOptions"
              @change="
                (...args) => {
                  typeChange(...args, item, index);
                }
              "
              :value="item.conditionType"
            ></p-select>
          </a-col>
          <a-col :span="8">
            <component
              :disabled="st == 1"
              :is="item.is"
              v-bind="item"
              @change="
                (...args) => {
                  handelChange(...args, item, index);
                }
              "
            />
          </a-col>
          <a-col :span="8" v-if="item.children">
            <p-search-modal
              targetClick
              :value="item.unitName"
              :disabled="st == 1 || !item.conditionValue"
              v-bind="item.children[~~item.conditionValue]"
              @change="
                (...args) => {
                  unitChange(...args, item, index);
                }
              "
            />
          </a-col>
          <a-col :span="1" v-if="st !== 1">
            <a-icon class="dynamic-delete-button" type="minus-circle-o" @click="() => remove(index)" />
          </a-col>
        </a-row>
        <a-dropdown v-if="st !== 1" style="width: 800px">
          <a-menu style="width: 100%" v-if="st !== 1 && options.STRATEGY_CONDITION_TYPE" slot="overlay" @click="addItem">
            <a-menu-item v-for="item in btnOptions" :key="item.value">
              {{ item.label }}
            </a-menu-item>
          </a-menu>
          <a-button block icon="plus">新增条件</a-button>
        </a-dropdown>
        <a-alert v-if="errorMsg" type="error" :message="errorMsg" banner />
      </template>
      <template slot="content" slot-scope="value, form">
        <a-space v-show="st !== 1" :contenteditable="false" :size="2" v-if="options.MESSAGE_ORDER_TYPE">
          <a-tag v-for="(objcet, index) in options.MESSAGE_ORDER_TYPE" @click="checkType(objcet.label, form, value)" :key="index"> {{ resultText(objcet.label) }}</a-tag>
        </a-space>
        <!-- @click="(event)=>{contentClick(event,form)}" -->

        <div
          class="ant-input code-container"
          ref="content"
          style="min-height: 86px; height: auto; display: block"
          :contenteditable="st === 1 ? false : true"
          @blur="(event) => contentBlur(event, form)"
          @keyup="(event) => contentClick(event, form)"
          @click="(event) => contentClick(event, form)"
          @select="(evnet) => contentClick(evnet, form)"
          v-html="contentHTML"
        ></div>
      </template>
    </p-grid-form>
    <!-- :hasRowCount="false" -->
    <p-button v-if="(st!==1)" style="width: 800px; margin: 10px 0" type="primary" @clickSync="addTableItem" icon="plus">新增通知人员</p-button>
    <p-table  v-if="st===1"  style="width: 800px"
      bordered
      :activeKey="activeID"
      :rowSelectType="0"
      :pagination="false"
      :filterDropdownColumn="false"
      :columns="viewTable"
      :dataSource="matchDataSource" />
    <p-table-edit-pro
      v-else
      ref="table"
      style="width: 800px"
      bordered
      :activeKey="activeID"
      :rowSelectType="0"
      :pagination="false"
      :filterDropdownColumn="false"
      :columns="matchTable"
      :dataSource.sync="matchDataSource"
      rowKey="_row_count"
    />
    </p-card>
</template>
<script>
const titleArr = ['', '查看', '新建', '修改', '复制'];

import { setFormItems, CONDITION_TYPE } from './config.js';
import { matchTable ,viewTable} from './tableConfig';

import { mainSaveData, getPageView } from '../../api';

import { createID } from '@/blocks/utils';

export default {
  props: {
    options: {
      //字典
      type: Object,
    },
    record: {
      //当前行数据
      type: Object,
    },
    mainId: {
      //主表ID
      type: null,
    },
    formName: {
      //主表：main，表细表：children
      type: 'main',
    },
    formExtendedField: {
      type: Array,
      default: () => [],
    },
    st: {
      type: Number,
      default: 0 /**0=不显示,1=查看,2=新建,3=修改,4=复制 */,
    },
  },
  data() {
    return {
      inputView: true,
      lastEditRange: null,
      errorMsg: null,
      viewTable:viewTable(this),
      matchTable: matchTable(this),
      CONDITION_TYPE: CONDITION_TYPE(this),
      vm: this,
      btnOptions: [],
      confirmLoading: false,
      list: [],
      formItems: [],
      activeID: '',
      matchDataSource: [],
      loading: false,
      contentHTML: '<div>' + this.contentView('您有新的运输任务${运单号}，请及时处理！') + '</div>',
    };
  },

  watch: {
    'options.STRATEGY_CONDITION_TYPE'(STRATEGY_CONDITION_TYPE) {
      if (STRATEGY_CONDITION_TYPE?.length > 0) {
        let form = this.form();
        let messageConfigConditionVOList = form.getFieldValue('messageConfigConditionVOList');
        this.btnOptions = this.selectBtnOptions(STRATEGY_CONDITION_TYPE, messageConfigConditionVOList);
      }
    },

    st(value) {
      /**0=不显示,1=查看,2=新建,3=修改,4=复制 */
      let form = this.form();
      this.lastEditRange = null;
      if (value === 2) {
        //新建
        form.resetFields();
        this.contentHTML = '<div>' + this.contentView('您有新的运输任务${运单号}，请及时处理！') + '</div>';
        form.setFieldsValue({
          content: '',
          messageConfigConditionVOList: [],
        });
        this.matchDataSource = [];
        this.btnOptions = this.options.STRATEGY_CONDITION_TYPE;
        return;
      } else if (value > 0) {
        this.formItems = setFormItems(this, this.formExtendedField);

        return getPageView(this, this.record.id).then((response) => {
          let form = this.form();
          if (response.success) {
            let { configNoticeToDTOList, configConditionDTOList ,sendType} = response.data;
            let formValue = response.data;
            formValue.sendType = sendType?.split(',') ?? [];

            this.contentHTML = this.contentView(formValue.content);
            this.matchDataSource = configNoticeToDTOList;
            formValue.messageConfigConditionVOList =
              configConditionDTOList?.map((item) => {
                const { id, strategyId, conditionType, conditionTypeName, conditionValue, conditionValueName, unitCode, unitId, unitName } = item;
                let CONDITION = CONDITION_TYPE(this)[item.conditionType];
                let obj = {
                  ...CONDITION,
                  id,
                  key: conditionType,
                  value: conditionValue,
                  conditionType,
                  conditionValue,
                  unitCode,
                  unitId,
                  unitName,
                  strategyId,
                };
                if (CONDITION.is == 'p-search-modal') {
                  obj.value = unitName;
                } else if (CONDITION.is == 'a-tree-select') {
                  obj.value = unitCode;
                }
                return obj;
              }) ?? [];


            this.btnOptions = this.selectBtnOptions(this.options.STRATEGY_CONDITION_TYPE, formValue.messageConfigConditionVOList);
            form.setFieldsValue(formValue);

          }
        });
      }
    },
    formExtendedField(value) {
      if (value.length > 0) {
        this.formItems = setFormItems(this, value);
      }
    },
  },
  computed: {
    selectOptions() {
      if (this.options?.STRATEGY_CONDITION_TYPE) {
        let keys = this.btnOptions.map((item) => {
          return item.value;
        });
        return this.options.STRATEGY_CONDITION_TYPE.map((item) => {
          if (!keys.includes(item.value)) {
            item.disabled = true;
          } else {
            item.disabled = false;
          }
          return item;
        });
      } else {
        return [];
      }
    },
    formList() {
      return this[this.formName + 'GetFormList'];
    },
    title() {
      return titleArr[this.st] + this.$route.meta.title;
    },
  },
  mounted() {
    this.formItems = setFormItems(this, this.formExtendedField);
  },
  methods: {
    addTableItem() {
      this.$refs.table.createRow(
        {
          noticeToId: '',
          noticeToName: '',
          type: '',
        },
        false
      );
    },
    contentClick(evnet, form) {
      let slelection = window.getSelection();
      this.lastEditRange = slelection.getRangeAt(0);
      // form.setFieldsValue({content:this.contentView( evnet.target.innerText)})
    },

    contentView(text) {
      text = text.replace(/\$\{[\s\S]*?\}/gi, function (value) {
        return ' <span>' + value + '</span> ';
      });
      return text;
    },
    contentBlur(value, form) {
      console.log(value);

      // form.setFieldsValue({ content: this.contentView(value.target.innerText) });
    },
    checkType(txt, form) {
      let edit = this.$refs.content;
      edit.focus();
      let selection = window.getSelection();

      let span = this.resultText(txt);
      let range = null;
      if (this.lastEditRange) {
        selection.removeAllRanges();
        selection.addRange(this.lastEditRange);
      }
      if (!selection.anchorNode) return false;
      let spanNode = document.createElement('span');
      spanNode.innerText = this.resultText(txt);
      let nullText = document.createTextNode('\u00A0');

      // '\&nbsp;'

      // range = document.createRange();
      // range.selectNodecontents(spanNode);
      console.log(selection.anchorNode.nodeName);
      if (selection.anchorNode.nodeName != '#text') {
        edit = selection.anchorNode;
      } else {
        edit = selection.anchorNode.parentNode;
      }

      if (edit.childNodes.length > 0 && edit.childNodes[0].nodeName != 'BR') {
        range = selection.getRangeAt(0);
        let reg = /\$\{[\s\S]*?\}/;
        if (reg.test(selection.anchorNode.wholeText)) {
          edit.replaceChild(spanNode, selection.anchorNode);
        } else {
          selection?.anchorNode.splitText?.(selection.anchorOffset);
          edit.insertBefore(spanNode, selection.anchorNode.nextSibling);
        }
        edit.insertBefore(nullText, spanNode.nextSibling);
      } else {
        edit.innerHTML = ' ';
        edit.appendChild(nullText);

        edit.insertBefore(spanNode, nullText);
      }

      range = document.createRange();
      range.selectNodeContents(nullText);

      //  spanNode.insertBefore(spanNode,selection.anchorNode)

      // edit.childNodes
      // 获取光标对象的范围界定对象，一般就是textNode对象

      var textNode = range.startContainer;
      // 获取光标位置
      var rangeStartOffset = range.startOffset;
      // 文本节点在光标位置处插入新的表情内容

      //textNode.insertData(rangeStartOffset, span);
      // 光标移动到到原来的位置加上新内容的长度
      range.setStart(textNode, rangeStartOffset + textNode.length);
      // 光标开始和光标结束重叠
      // range.collapse(true);
      // 清除选定对象的所有光标对象
      selection.removeAllRanges();
      // 插入新的光标对象
      selection.addRange(range);

      //selection.selectAllChildren(textNode.parentNode)

      this.lastEditRange = selection.getRangeAt(0);

      // collapsed: true
      // commonAncestorContainer: text
      // endContainer: text
      // endOffset: 6
      // startContainer: text
      // startOffset: 6
    },
    resultText(txt) {
      return '${' + txt + '}';
    },

    typeChange(value, label, options, sitem, index) {
      this.errorMsg = null;
      // let _item = this.options?.STRATEGY_CONDITION_TYPE.find((item) => item.value == value)
      let form = this.form();
      let messageConfigConditionVOList = form.getFieldValue('messageConfigConditionVOList');
      let item = messageConfigConditionVOList[index];
      let CONDITION = CONDITION_TYPE(this)[value];

      delete item.suffixIcon;
      delete item.treeData;
      delete item.replaceFields;
      delete item.remoteUrl;
      item.children = null;
      for (let key in CONDITION) {
        item[key] = CONDITION[key];
      }
      item.key = value;
      item.value = undefined;
      item.conditionType = value; //承运商策略条件类型 ,
      item.conditionValue = undefined; //承运商策略条件值
      item.unitCode = null;
      item.unitName = null;
      item.unitId = null;
      // item={...item}
      form.setFieldsValue({ messageConfigConditionVOList });
      this.btnOptions = this.selectBtnOptions(this.options.STRATEGY_CONDITION_TYPE, messageConfigConditionVOList);
    },
    unitChange(...args) {
      this.errorMsg = null;
      let index = args[args.length - 1];
      let form = this.form();
      let messageConfigConditionVOList = form.getFieldValue('messageConfigConditionVOList');
      let item = messageConfigConditionVOList[index];
      if (item.children) {
        let [vode, label, data] = args;
        item.unitCode = null;
        item.unitName = null;
        item.unitId = null;
        if (data[0]) {
          let { id, code } = data[0];
          item.unitCode = code;
          item.unitName = label;
          item.unitId = id;
        }
      }
      form.setFieldsValue({ messageConfigConditionVOList });
    },
    handelChange(...args) {
      this.errorMsg = null;
      let index = args[args.length - 1];
      let form = this.form();
      let messageConfigConditionVOList = form.getFieldValue('messageConfigConditionVOList');
      let item = messageConfigConditionVOList[index];
      item.unitCode = null;
      item.unitName = null;
      item.unitId = null;
      item.conditionValue = undefined;
      if (item.is == 'p-select') {
        let [value, label, options] = args;
        item.value = value;
        item.conditionValue = value;
      } else if (item.is == 'p-search-modal') {
        let [vode, label, data] = args;
        if (data[0]) {
          let { cargoOwnerId, cargoOwnerCode } = data[0];
          item.unitCode = cargoOwnerCode;
          item.unitName = label;
          item.unitId = cargoOwnerId;
          item.value = label;
          item.conditionValue = undefined;
        }
      } else if (item.is == 'a-tree-select') {
        let [value, label, extra] = args;
        item.unitCode = value;
        item.value = value;
        item.unitName = label[0];
        item.unitId = extra.triggerNode.eventKey;
        item.conditionValue = null;
      }
      form.setFieldsValue({ messageConfigConditionVOList });
    },
    selectBtnOptions(STRATEGY_CONDITION_TYPE, messageConfigConditionVOList) {
      let form = this.form();
      if (form && STRATEGY_CONDITION_TYPE && messageConfigConditionVOList) {
        messageConfigConditionVOList = messageConfigConditionVOList.map((item) => item.key);
        STRATEGY_CONDITION_TYPE = STRATEGY_CONDITION_TYPE.filter((item) => {
          return !messageConfigConditionVOList.includes(item.value);
        });
        return STRATEGY_CONDITION_TYPE;
      }

      return [];
    },
    remove(i) {
      let form = this.form();
      let messageConfigConditionVOList = form.getFieldValue('messageConfigConditionVOList');
      messageConfigConditionVOList.splice(i, 1);
      form.setFieldsValue({ messageConfigConditionVOList });
      this.btnOptions = this.selectBtnOptions(this.options.STRATEGY_CONDITION_TYPE, messageConfigConditionVOList);
    },
    addItem(e) {
      let item = this.options?.STRATEGY_CONDITION_TYPE.find((item) => item.value == e.key);
      let value = item.value;

      item = this.CONDITION_TYPE[item.value];
      if (!item) return;

      item = {
        id: 'new-' + createID(),
        key: value,
        ...item,
        conditionType: value, //承运商策略条件类型 ,
        conditionValue: undefined, //承运商策略条件值
        unitCode: null,
        unitName: null,
        unitId: null,
        value: undefined,
      };

      let form = this.form();
      let messageConfigConditionVOList = form.getFieldValue('messageConfigConditionVOList');
      messageConfigConditionVOList = messageConfigConditionVOList.concat([item]);

      form.setFieldsValue({ messageConfigConditionVOList });

      this.btnOptions = this.selectBtnOptions(this.options.STRATEGY_CONDITION_TYPE, messageConfigConditionVOList);
    },
    getFieldsValue() {
      return this.form().getFieldsValue();
    },
    form() {
      return this.$refs?.grid?.form??null;
    },
    save() {
      let form = this.form();
      let _this = this;
      _this.errorMsg = null;
      form.validateFields((error, value) => {
        if (error) return;
        if (value.messageConfigConditionVOList.length === 0) {
          return _this.$message.error('承运方匹配策略条件不为空');
        }

        value.messageConfigConditionVOList = value.messageConfigConditionVOList.map((item) => {
          let {
            conditionType, //承运商策略条件类型 ,
            conditionValue, //承运商策略条件值
            unitCode,
            unitName,
            unitId,
            id,
            strategyId,
            value,
            children,
            title,
          } = item;
          if (children) {
            if (!value || !unitId || !unitName || !unitCode) {
              if (!unitName && value) {
                title = title.replace('类型', children?.label[value] ?? '');
              }
              this.$message.error('请选择' + title);
              _this.$set(_this, 'errorMsg', '请选择' + title);
              error = true;
            }
          } else {
            if (!value) {
              this.$message.error('请选择' + title);
              _this.$set(_this, 'errorMsg', '请选择' + title);
              error = true;
            }
          }

          let obj = {
            conditionType, //承运商策略条件类型 ,
            conditionValue, //承运商策略条件值
            unitCode,
            unitName,
            unitId,
          };
          if (this.st === 3) {
            obj.id = id.indexOf('new-') > -1 ? null : id;
            obj.strategyId = strategyId || null;
          }

          return obj;
        });
        if (error) return;

        value.messageConfigNoticeToVOList = _this.matchDataSource;
        // this.contentHTML=_this.$refs?.content.innerText

        return mainSaveData(this, { ...value,sendType:value.sendType?.join(',')??value.sendType, content: _this.$refs?.content.innerText }, this.st).then((res) => {
          if (res.success) {
            setTimeout(() => {
              this.back(res.data || value.id, true);
            }, 1000);
          }
        });
      });
    },
    back(id, isReload = false) {
      this.matchDataSource = [];
      this.lastEditRange = null;
      this.$emit('back', id, isReload);
    },
  },
};
</script>
<style>
.dynamic-delete-button {
  cursor: pointer;
  position: relative;
  top: 4px;
  font-size: 24px;
  color: #999;
  transition: all 0.3s;
}

.dynamic-delete-button:hover {
  color: #777;
}

.dynamic-delete-button[disabled] {
  cursor: not-allowed;
  opacity: 0.5;
}
.code-container span {
  color: #c41d7f;
}
.code-color {
  color: #c41d7f;
}
</style>
