<template>
  <div class='AbnormalPriceMonitoreStrategy'>
    <div class="quickOperation" data-key='PROD_PRICE_MONITOR_EDIT'>
      快捷操作：
      <Button
        type="fcdefault"
        style="margin-right:8px"
        @click="saveAll"
      >
        保存
      </Button>
      <!-- <Button type="fcdefault" style="margin-right:8px" @click="refreshParams">刷新</Button> -->
      <Button
        type="fcdefault"
        @click="backToList"
      >
        返回
      </Button>
    </div>
    <div class="content">
      <div
        v-for="(item,tabId) in tabList"
        :key="tabId"
        class="block"
      >
        <foldPanel
          v-model="item.blockShow"
          :title="item.tabtext"
          :explain="item.explainText"
        >
          <div
            slot="content"
            class="block"
          >
            <div class="item">
              <Row>
                <div
                  v-for="(i,cindex) in tabList[tabId].list"
                  :key="cindex"
                  class="form"
                >
                  <Col
                    span="8"
                    v-if="i.standard"
                  >
                  <div
                    v-if="i.title"
                    :class="{'title':true,'order-setting-input-error':i.required}"
                  >{{ i.title }}
                    <Tooltip
                      max-width="200"
                      :content="i.explainContent"
                      placement="bottom"
                    >
                      <img
                        v-if="i.explain"
                        class="img-framelanflag"
                        src="../../../assets/icon/help.png"
                      >
                    </Tooltip>
                  </div>
                  <DatePicker
                    :value="i.VALUE"
                    v-if='i.SKEY=="strategyTimeRange"'
                    type="datetimerange"
                    format="yyyy-MM-dd HH:mm:ss"
                    placeholder="请选择时间"
                    style="width: 100%;max-width:400px;min-width: 180px;"
                    transfer
                    @on-change="rangeDate"
                  ></DatePicker>
                  <arkDropMultiSelectFilter
                    ref="arkDropMultiSelectFilter"
                    class="shopDropMultiSelectFilter"
                    v-model="dropDownShopValue"
                    v-else-if="i.SKEY=='shop_name'"
                    :props-data="propsData"
                    :url="Url"
                    :table-request="TableRequest"
                    :http="network"
                    @on-change="DropShopvalueChange"
                  ></arkDropMultiSelectFilter>
                  <!-- <DropMultiSelectFilter
                    class="input_box"
                    v-else-if="i.SKEY=='shop_name'"
                    :data="shopTrue.shopData"
                    :totalRowCount="shopTrue.shopData.totalRowCount"
                    :showColnameKey="'isak'"
                    :defaultSelected="shopTrue.defaultSelected"
                    @on-page-change="changePageTrueShop"
                    @on-input-value-change="InputValueChangeTrueShop"
                    @on-popper-show="searchTrueShopData"
                    @on-fkrp-selected="checkDataTrueShop"
                    @on-clear="clearTrueShop"
                    :dataEmptyMessage="shopTrue.dataEmptyMessage"
                    :columns="shopTrue.columnsShop"
                    :AutoData="shopTrue.AutoDataShop">
                  </DropMultiSelectFilter> -->
                  <!-- :multiple="i.SKEY=='shop_name'?true:false"
                    :filterable="i.SKEY=='shop_name'?true:false" -->
                  <Select
                    v-model="i.VALUE"
                    :clearable='i.clearable'
                    :disabled="i.disabled"
                    class="input_box"
                    v-else-if="i.SKEY=='orderTimeType'"
                    @on-query-change="checkInputSKU($event,i)"
                  >
                    <Option
                      v-for="d in i.optionList"
                      :value="d.value"
                      :key="d.value"
                    >{{ d.label }}</Option>
                  </Select>
                  <Input
                    v-else-if="i.SKEY=='strategyName'"
                    class="input_box"
                    v-model="i.VALUE"
                    placeholder="请输入策略名称"
                    :disabled="i.disabled"
                    @on-keypress='noSpaces($event,i)'
                  />
                  </Col>
                </div>
              </Row>
            </div>

            <div style="min-width: 1348px;">
              <panel-form
                tableName="EDITABNORMALPRICEMONITORESTRATEGY"
                ref="objform"
                class="strategy-panel"
                @on-changeForm="onChangeForm"
                :labelWidth="80"
                display="flex"
                :noResize="true"
                :readonly="panelFormData.objreadonly"
                :is-main-table="panelFormData.isMainTable"
                :defaultData="panelFormData.data"
              >
              </panel-form>
            </div>
          </div>
        </foldpanel>
      </div>
    </div>
    <div
      class="tableArea priceMonitor"
      v-if="showDetailTable"
    >
      <Tabs
        type="card"
        :value='tabName'
        v-model='tabName'
      >
        <TabPane
          label="明细"
          name="name1"
        >
          <Row style="display: flex;
                justify-content: space-around;
                align-items: center;
                height: 48px;
                margin-bottom: 16px;
                background: #F8F8F8;">
            <Col span="5">
            <div style="display: flex;align-items: center;">
              <Tooltip
                max-width="200"
                content="商品条码优于商品编码判断、商品编码优于商品品牌判断"
                placement="bottom"
              >
                <img
                  class="img-framelanflag"
                  src="../../../assets/icon/help.png"
                >
              </Tooltip>
              <label style="width: 60px;text-align:right;margin-right:4px;">
                <span style='color: red;'>*</span>监控维度</label>
              <Select
                style="width:220px"
                v-model="detail.PriceMonitoreDimension"
                @on-change="selectPriceMonitoreDimension"
                @on-enter="addReturnGoods"
                filterable
                clearable
              >
                <Option
                  v-for="(option,index) in PriceMonitoreDimensionList"
                  :key="index"
                  :value="option.value"
                >{{option.label}}</Option>
              </Select>
            </div>
            </Col>
            <Col span="5">
            <div
              style="display: flex;align-items: center;"
              v-if='detail.PriceMonitoreDimension'
            >
              <label style="width: 70px;text-align:right;margin-right:4px;"><span style='color: red;'>*</span>监控维度值</label>
              <DropDownSelectFilter
                :single="true"
                width='220px'
                class="input_box"
                :data="MonitorDimensionValue.shopData"
                :totalRowCount="MonitorDimensionValue.shopData.totalRowCount"
                :showColnameKey="'isak'"
                :defaultSelected="MonitorDimensionValue.defaultSelected"
                @on-page-change="changePageShop($event)"
                @on-input-value-change="InputValueChangeShop($event)"
                @on-popper-show="searchShopData()"
                @on-fkrp-selected="checkDataShop($event)"
                @on-focus="focusInputValueChangeShop($event)"
                @on-blur="changeDataShop($event)"
                @on-clear="clearDataShop()"
                :dataEmptyMessage="MonitorDimensionValue.dataEmptyMessage"
                :columns="MonitorDimensionValue.columns"
                :AutoData="MonitorDimensionValue.AutoData"
              >
              </DropDownSelectFilter>
            </div>
            </Col>
            <Col span="5">
            <div style="display: flex;align-items: center;">
              <label style="width: 60px;text-align:right;margin-right:4px;"><span style='color: red;'>*</span>监控类型</label>
              <Select
                style="width:220px"
                v-model="detail.MonitoreType"
                @on-change="selectMonitoreType"
                @on-enter="addReturnGoods"
                filterable
                clearable
              >
                <Option
                  v-for="(option,index) in MonitoreTypeList"
                  :key="index"
                  :value="option.value"
                >{{option.label}}</Option>
              </Select>
            </div>
            </Col>
            <Col span="5">
            <div
              style="display: flex;align-items: center;"
              v-if='detail.MonitoreType'
            >
              <Tooltip
                max-width="200"
                :content="MonitorSetValueContent"
                placement="bottom"
              >
                <img
                  class="img-framelanflag"
                  src="../../../assets/icon/help.png"
                >
              </Tooltip>
              <label style="width: 80px;text-align:right;margin-right:4px;"><span style='color: red;'>*</span>监控设置值</label>
              <Input
                style="width:220px"
                :regx="detail.MonitoreType=='1'?regx:regx1"
                v-model="detail.MonitorSetValue"
                @on-enter="addReturnGoods"
              ></Input><span v-if='[1,3].includes(detail.MonitoreType)'>%</span>
            </div>
            </Col>
            <Col span="2">
            <Button
              type="primary"
              icon="md-return-left"
              @click="addReturnGoods"
            >添加明细</Button>
            </Col>
          </Row>
          <div class="handleBtn">
            <div
              class="handleItem"
              @click="deleteReturnGoods"
            >【删除】</div>
            <div
              class="handleItem"
              @click="importStrategyDetailExcel"
            >【导入】</div>
            <div
              class="handleItem"
              @click="exportStrategyDetailExcel"
            >【导出】</div>
            <div class='searchList'>
              <Select
                style="width:90px"
                v-model="MonitoreDimensionType"
                @on-enter="getpageDetailList('table')"
                filterable
                clearable
              >
                <Option
                  v-for="(option,index) in PriceMonitoreDimensionList"
                  :key="index"
                  :value="option.value"
                >{{option.label}}</Option>
              </Select>
              <Input
                style="width:180px"
                v-model="MonitoreDimensionMsg"
                @on-enter="getpageDetailList('table')"
              ></Input>
              <Button
                type="fcdefault"
                style="width:54px;height:24px;line-height:5px;margin-left:2px;margin-top:2px;padding:unset;"
                @click="getpageDetailList('table')"
              >搜索</Button>
            </div>
          </div>
          <Table
            height="320"
            :columns="returnColumns"
            :data="currentReturnData"
            @on-select="selectReturnData"
            @on-select-cancel="selectReturnCancel"
            @on-select-all="selectReturnDataAll"
            @on-select-all-cancel="selectReturnDataCancel"
          ></Table>
          <div class="pageContent">
            <Page
              size="small"
              :current="returnCurrentPage"
              show-elevator
              :total="totalReturn"
              show-total
              show-sizer
              @on-change="changePageReturn"
              @on-page-size-change="changeSizeReturn"
            />
          </div>
        </TabPane>

        <TabPane
          label="监控范围"
          name="name2"
        >
          <Row style="display: flex;padding: 0 16px;align-items: center;height: 48px;margin-bottom: 16px;background: #F8F8F8;">
            <Col
              span="4"
              class="form-item"
            >
            <label>
              <span class="form-label">品牌</span>
            </label>
            <Select
              class="value-width"
              v-model="detailForm.BRANDID"
              style="width:200px"
              filterable
              remote
              clearable
              @on-query-change="handleQueryChange"
              :remote-method="handleFindBrand"
            >
              <Option
                v-for="item in brandList"
                :value="item.value"
                :key="item.value"
              >{{ item.label }}</Option>
            </Select>
            </Col>
            <Col
              span="4"
              class="form-item"
            >
            <Tooltip
              max-width="200"
              content="可以维护多个，多个分隔支持逗号、分号、空格"
              placement="bottom"
            >
              <img
                class="img-framelanflag"
                src="../../../assets/icon/help.png"
              >
            </Tooltip>
            <label>
              <span class="form-label">季节</span>
            </label>
            <Input
              class="value-width"
              v-model="detailForm.SEASON"
              placeholder="多个季节可用英文分号分隔"
            />
            </Col>
            <Col
              span="4"
              class="form-item"
            >
            <Tooltip
              max-width="200"
              content="可以维护多个，多个分隔支持逗号、分号、空格"
              placement="bottom"
            >
              <img
                class="img-framelanflag"
                src="../../../assets/icon/help.png"
              >
            </Tooltip>
            <label>
              <span class="form-label">年份</span>
            </label>
            <Input
              class="value-width"
              v-model="detailForm.YEAR"
              :regx="/^[0-9;]+$/i"
              placeholder="多个年份可用英文分号分隔"
            />
            </Col>
            <Col
              span="4"
              class="form-item"
            >
            <Tooltip
              max-width="200"
              content="可以维护多个，多个分隔支持逗号、分号、空格"
              placement="bottom"
            >
              <img
                class="img-framelanflag"
                src="../../../assets/icon/help.png"
              >
            </Tooltip>
            <label>
              <span class="form-label">大类</span>
            </label>
            <Input
              class="value-width"
              v-model="detailForm.CATEGORY"
              placeholder="多个大类可用英文分号分隔"
            />
            </Col>
            <Col
              span="7"
              class="form-item"
            >
              <span style='color: red;'>*</span>
              <Select
                style="width:212px"
                v-model="detailForm.MONITORTYPE"
                @on-change="changeAlertType"
              >
                <Option
                  v-for="item in alertList"
                  :value="item.value"
                  :key="item.value"
                >{{ item.label }}</Option>
              </Select>
              <Input
                style="width:100px"
                v-model="detailForm.MONITORVALUE"
                :regx="detailForm.MONITORTYPE === '1'? /^(?:100|[1-9]\d|\d)$/: /^\d+$/"
              />
              <span v-if="['1', '3'].includes(detailForm.MONITORTYPE)">%</span>
            </Col>
            <Col
              span="1"
              class="form-item"
            >
            <Button
              type="primary"
              @click="addMonitor"
            >添加</Button>
            </Col>
          </Row>
          <div class="handleBtn">
            <div
              class="handleItem"
              @click="deleteMonitor({ deleteType:'monitor_area' })"
            >【删除】</div>
            <div
              class="handleItem"
              @click="importHandle({ importType: 'monitor_area' })"
            >【导入】</div>
            <div
              class="handleItem"
              @click="exportHandle({exportType: 'monitor_area'})"
            >【导出】</div>
          </div>
          <div class="table-wrap">
            <arkCommonTableByAgGrid
              height="320px"
              :columns="monitorColumns"
              :data="monitorData"
              @on-selection-change="onSelectionChanged"
            >
            </arkCommonTableByAgGrid>
            <div class="pageContent">
              <Page
                size="small"
                :current="monitorCurrentPage"
                show-elevator
                :total="monitorTotalPage"
                show-total
                show-sizer
                @on-change="onPageChange"
                @on-page-size-change="onPageSize"
              />
            </div>
          </div>
        </TabPane>
        <TabPane
          label="排除商品"
          name="excludeProd">
          <div id="customDetailFormWrap1" class="product-price-custom-tab-wrap" style="position:relative;">
            <panel-form
              ref="tabName1Form"
              style="flex:1"
              table-name="DETAIL_ONE"
              class="strategy-panel"
              display="flex"
              :label-width="123"
              :no-resize="true"
              :readonly="excludeProdForm.objreadonly"
              :is-main-table="excludeProdForm.isMainTable"
              :default-data="excludeProdForm.data"
              @on-changeForm="onChangeDetailForm"
              @on-keydown="onKeydownForm"
            />
            <Button type="primary" style="position:absolute;z-index:1;right:16px;top:50%;transform:translateY(-50%)" @click="saveDetailHandle">添加</Button>
          </div>
          <div class="global-custom-table-wrap">
            <div class="detail-collection">
              <div class="detail-top">
                <ul class="detail-buttons" style="padding:6px">
                  <a id="actionDELETE" @click="deleteMonitor({ deleteType:'exclude_prod' })">【删除】</a>
                  <a id="actionImport" @click="importHandle({ importType: 'exclude_prod' })">【导入】</a>
                  <a id="actionDownload" @click="exportHandle({exportType: 'exclude_prod'})">【导出】</a>
                </ul>
              </div>
            </div>
            <arkCommonTableByAgGrid
              height="320px"
              :columns="excludeColumns"
              :data="excludeData"
              @on-selection-change="onSelectChanged"
            />
          </div>
          <div class="pageContent" style="padding-bottom:20px;">
            <Page
              size="small"
              show-elevator
              show-total
              show-sizer
              :current="excludePageNum"
              :total="excludeTotal"
              @on-change="excludePageChange"
              @on-page-size-change="excludeSizeChange"
              />
          </div>
        </TabPane>
      </Tabs>
    </div>
    <Modal
      v-model="showTip"
      mask
      :mask-closable="maskClosable"
      title="警告"
      title-align="left"
      class-name="showTipModel"
      width="400px"
      @on-ok="closePage"
    >
      <p><i class="iconfont iconbj_doubt fcWarning " />修改的数据未保存，确定返回？</p>
    </Modal>
    <PriceMonitorDetailImport
      :type='tabName'
      :visible='PriceMonitorDetailvisible'
      @closeActionDialog='closeActionDialog'
      :pageMsgId='pageMsgId'
      :customImport="customImport"
      :title="subTableName"
      :tablename="subTable"
    ></PriceMonitorDetailImport>
  </div>
</template>
<script>
import foldPanel from '../../customizedContent/FoldPanel.vue'; // 折叠面板组件
import ShrinkOrExtend from '../../customizedContent/shrinkOrExtend' //收缩伸展搜索条件组件
import tableFaker from '../../customizedContent/tableFaker.vue'; //表格组件
import PriceMonitorDetailImport from '../../modal/systemImport/PriceMonitorDetailImport.vue'; // 参与商品导入弹框
import debounce from 'lodash/debounce'
import strategyMixin from './mixins/monitorStrategy'
// 新增和编辑公用的 排除商品
import excludeProduct from './mixins/excludeProducts';

import { DispatchEvent, R3_IMPORT } from '../../../assets/js/__utils__/dispatchEvent';

const R3 = window.R3;
const { network, urlSearchParams, store } = R3;
export default {
  data() {
    return {
      PriceMonitorDetailvisible: false,
      tabName: 'name1',
      selectReturnSKUID: '',//策略明细sku下拉框双向数据绑定
      returnGoodsNum: 1,//策略明细数量

      regx: /^(0|100|([1-9][0-9]?)|(0|[1-9][0-9]?)(?:\.\d{0,2}))?$/, // 0-100带两位小数的正数
      regx1: /^\d{0,15}(\.[0-9]{0,2})?$/, // 两位小数的正数
      MonitoreDimensionType: '',
      MonitoreDimensionMsg: '',
      tabList: [
        {
          tabId: '1',
          tabtext: '基本信息',
          blockShow: true,
          list: [
            {
              ID: '',
              SKEY: 'strategyName',
              title: '策略名称:',
              VALUE: '',
              company: '',
              tips: '',
              disabled: false,
              standard: true,//标准输入框长度
              flag: true, // 控制必填校验样式展示
              required: true, // 是否为必填项
              explain: false, //是否有解释
            },
            {
              ID: 'T_V_IESSHOP',
              SKEY: 'shop_name',
              title: '使用店铺:',
              VALUE: '',
              defaultvalue: '',
              company: '',
              tips: '',
              clearable: true,
              disabled: false,
              flag: true, // 控制必填校验样式展示
              required: true, // 是否为必填项
              standard: true,//标准输入框长度
              optionList: []
            },
            {
              SKEY: 'strategyTimeRange',
              title: '起止时间:',
              VALUE: [],
              defaultvalue: '',
              company: '',
              tips: '',
              disabled: false,
              required: true, // 是否为必填项
              standard: true,//标准输入框长度
              flag: true, // 控制必填校验样式展示
            },
            {
              // SKEY: 'orderTimeType',  // 不需要再界面上展示，所以注释掉.
              // title: '策略类型',
              VALUE: '1',
              defaultvalue: '1',
              company: '',
              tips: '',
              clearable: false,
              explain: true, //是否有解释
              disabled: false,
              required: true, // 是否为必填项
              standard: true,//标准输入框长度
              flag: true, // 控制必填校验样式展示
              explainContent: '大促类型策略优于日常类型先去执行',//解释文字
              optionList: [
                { label: '大促', value: '2' },
                { label: '日常', value: '1' }
              ]
            },
          ]
        },
      ],
      returnColumns: [ //策略明细
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          type: 'index',
          align: 'center',
          title: '序号',
        },
        {
          title: '监控维度',
          align: 'center',
          key: 'PriceMonitoreDimension',
          render: (h, params) => {
            const vm = this;
            return h('Select', {
              style: {
                width: '150px',
                zIndex: 999,
              },
              props: {
                transfer: true,
                value: params.row.PriceMonitoreDimension, // 获取选择的下拉框的值
              },
              on: {
                'on-change': (e) => {
                  let chengeData = vm.currentReturnData[params.index]
                  vm.returnData.forEach((item) => {
                    if ((item.id == chengeData.id)) {
                      item.PriceMonitoreDimension = e;
                      item.MonitorDimensionList.VALUE = '';
                      item.MonitorDimensionList.defaultSelected = [];
                      item.MonitorDimensionValue = '';
                      item.MonitorDimensionValueID = '';
                    }
                  })
                  vm.totalReturn = vm.returnData.length;
                  let startIndex = vm.pageSizeReturn * (vm.returnCurrentPage - 1)
                  let endIndex = startIndex + vm.pageSizeReturn
                  vm.currentReturnData = vm.returnData.slice(startIndex, endIndex) //当前页面显示明细
                }
              }
            },
              vm.PriceMonitoreDimensionList.map(item => h('Option', {
                props: {
                  value: item.value, // 绑定的值
                }
              }, item.label)
              ));
          }
        },
        {
          title: '监控维度值',
          align: 'center',
          key: 'MonitorDimensionValue',
          render: (h, params) => {
            const vm = this;
            return h('DropDownSelectFilter', {
              style: {
                width: '240px',
                margin: '0 auto',
                zIndex: 999,
              },
              props: {
                transfer: true,
                // value: , // 获取选择的下拉框的值
                single: true,
                data: params.row.MonitorDimensionList.shopData,
                totalRowCount: params.row.MonitorDimensionList.shopData.totalRowCount,
                showColnameKey: 'isak',
                dataEmptyMessage: params.row.MonitorDimensionList.dataEmptyMessage,
                columns: params.row.MonitorDimensionList.columns,
                AutoData: params.row.MonitorDimensionList.AutoData,
                defaultSelected: params.row.MonitorDimensionList.defaultSelected,
                isBackRowItem: true,
              },
              on: {
                'on-popper-show': (e) => {
                  this.searchShopData(params, 'table')
                },
                'on-page-change': (e) => {
                  this.changePageShop(e, params, 'table')
                },
                'on-input-value-change': (e) => {
                  this.InputValueChangeShop(e, params, 'table')
                },
                'on-fkrp-selected': (e) => {
                  this.checkDataShop(e, params, 'table')
                  let chengeData = vm.currentReturnData[params.index]
                  vm.returnData.forEach((item) => {
                    if ((item.id == chengeData.id)) {
                      item.MonitorDimensionList.VALUE = e[0].Label;
                      item.MonitorDimensionList.defaultSelected = [{ ID: e[0].ID, Label: e[0].Label }];
                      item.MonitorDimensionValue = e[0].ID;
                      item.MonitorDimensionValueID = e[0].ID;
                    }
                  })
                  vm.totalReturn = vm.returnData.length;
                  let startIndex = vm.pageSizeReturn * (vm.returnCurrentPage - 1)
                  let endIndex = startIndex + vm.pageSizeReturn
                  vm.currentReturnData = vm.returnData.slice(startIndex, endIndex) //当前页面显示明细
                  console.log(params.row)
                },
                'on-focus': (e) => {
                  this.focusInputValueChangeShop(e, params, 'table')
                },
                'on-clear': (e) => {
                  this.clearDataShop(params, 'table')
                },
              }
            },);
          }
        },
        {
          title: '监控类型',
          align: 'center',
          key: 'MonitoreType',
          render: (h, params) => {
            const vm = this;
            return h('Select', {
              style: {
                width: '150px',
                zIndex: 999,
              },
              props: {
                transfer: true,
                value: params.row.MonitoreType, // 获取选择的下拉框的值
              },
              on: {
                'on-change': (e) => {
                  let chengeData = vm.currentReturnData[params.index]
                  vm.returnData.forEach((item) => {
                    if ((item.id == chengeData.id)) {
                      item.MonitoreType = e;
                      item.MonitorSetValue = '';
                    }
                  })
                  vm.totalReturn = vm.returnData.length;
                  let startIndex = vm.pageSizeReturn * (vm.returnCurrentPage - 1)
                  let endIndex = startIndex + vm.pageSizeReturn
                  vm.currentReturnData = vm.returnData.slice(startIndex, endIndex) //当前页面显示明细
                }
              }
            },
              vm.MonitoreTypeList.map(item => h('Option', {
                props: {
                  value: item.value, // 绑定的值
                }
              }, item.label)
              ));
          }
        },
        {
          title: '监控设置值',
          align: 'center',
          key: 'MonitorSetValue',
          render: (h, params) => {
            return h(
              'div',
              {
                style: {
                  width: '200px',
                  margin: '0 auto'
                },
              },
              [
                h('Input',
                  {
                    style: {
                      width: '100px',
                      marginLeft: params.row.MonitoreType == '1' ? '16px' : '0px',
                    },
                    props: {
                      value: params.row.MonitorSetValue,
                    },
                    on: {
                      'on-blur': (event) => {
                        let chengeData = this.currentReturnData[params.index]
                        this.returnData.forEach(item => {
                          if ((item.id == chengeData.id)) {
                            item.MonitorSetValue = event.target.value
                          }
                        })
                        // 截取数组
                        let startIndex = this.pageSizeReturn * (this.returnCurrentPage - 1)
                        let endIndex = startIndex + this.pageSizeReturn
                        this.totalReturn = this.returnData.length// 总条数
                        this.currentReturnData = this.returnData.slice(startIndex, endIndex)
                      }
                    }
                  },
                ),
                h('span',
                  {
                    style: {
                      display: [1, 3].includes(params.row.MonitoreType) ? 'inline-block' : 'none',
                      marginLeft: '6px'
                    },
                  },
                  '%')
              ]
            );
          },
        },
      ],
      tableHeight: '200',//表格高度

      currentReturnData: [],//当前显示策略明细明细
      returnData: [],
      returnDataNoSame: [],//弹窗中没有的策略明细
      submitArrReturn: [],//选中的策略明细
      // 策略明细page
      returnCurrentPage: 1,
      totalReturn: 0, // 总条数
      currentPageReturn: 1, // 页码
      pageSizeReturn: 10, // 每页的条数

      // 选择商品
      mask: true,
      closable: true,
      maskClosable: false,
      hideFoot: true,
      shrinkHeight: '58px',
      currentValue: false,//默认收缩

      showTip: false,
      showDetailTable: true, // 展示商品明细
      startTime: '',  // 活动开始时间
      endTime: '', // 活动结束时间

      detail: {
        PriceMonitoreDimension: '', // 监控维度
        MonitorDimensionValue: '', // 监控维度值
        MonitoreType: 1, // 监控类型
        MonitorSetValue: '', // 监控设置值
      },
      PriceMonitoreDimensionList: [ // 监控维度
        {
          label: '商品品牌',
          value: 1
        },
        {
          label: '商品编码',
          value: 2
        },
        {
          label: '商品条码',
          value: 3
        },
      ],
      MonitoreTypeList: [ // 监控类型
        {
          label: '预警折扣（成交价/平台销售价）',
          value: 1
        },
        {
          label: '预警折扣（成交价/系统标准价）',
          value: 3
        },
        {
          label: '预警成交单价',
          value: 2
        },
      ],
      MonitorDimensionValue: {
        VALUE: '', //字段值
        clearable: true,
        tableName: 'T_IESBRAND',//表名
        currentIndex: 0,//当前页码
        dataEmptyMessage: '数据加载中...', // 无数据的提示
        columns: ['name', 'value'],// 展现的组
        AutoData: [],//模糊搜索
        defaultSelected: [],//默认数据
        shopData: {},
      },
      MonitorSetValueContent: '根据商品成交单价/平台售价和预警折扣做比对', // 监控设置值解释

      //编辑页面
      pageMsgId: '', // 当前策略id

      oldBaseMsg: {
        name: '', // 策略名称
        shopid: '', // 店铺
        startTime: '', // 开始时间
        endTime: '', // 结束时间
        type: '', // 策略类型
      },

      shopTrue: {
        shopData:{},//店铺下拉数据
        currentIndex:0,//当前也从第几条索引开始
        dataEmptyMessage: '数据加载中...', // 无数据的提示
        columnsShop:['name','value'],// 店铺数据展现的组
        AutoDataShop:[],//店铺模糊搜索数据
        defaultSelected:[],//编辑页面默认值
      },
      dropDownShopValue: '',
      network,
      propsData: {
        pageSize: 10,
        item: {}
      },
      TableRequest: {
        isdroplistsearch: true,
        refcolid: 202934,
      },
      eventFun: {
        'on-blur': (even) => {
          setTimeout(() => {
            if (!Array.isArray(this.dropDownShopValue)) {
              even.target.value = '';
              this.$emit('change', []);
            }
          }, 200);
        }
      },
      Url: {
        autoUrl: '/p/cs/fuzzyquerybyak',
        tableUrl: 'p/cs/QueryList',
        tableSearchUrl: '/p/cs/newQueryList'
      }
    };
  },
  mixins: [strategyMixin, excludeProduct],

  components: {
    foldPanel,
    ShrinkOrExtend,
    tableFaker,
    PriceMonitorDetailImport
  },
  created() {
    this.pageMsgId = window.parent.vm._route.params.customizedModuleId;
    this.getStategyDetail();
    this.getpageDetailList();
    this.getQuery('T_V_IESSHOP', { isactive: ["=Y"] })// 初始查询店铺名称列表
    // this.getBrandList()
    this.getMonitorList()
    this.getExcludeList();// 获取排除商品列表
  },
  methods: {
    // 排除商品翻页
    excludePageChange(val) {
      this.excludePageNum = val;
      this.getExcludeList();
    },

    // 每页条数
    excludeSizeChange(val) {
      this.excludePageSize = val;
      this.excludePageNum = 1;
      this.getExcludeList();
    },
    // 获取排除商品列表
    async getExcludeList() {
      const params = {
        table: 'T_SKUPRICEEXCLUDEITEM',
        startindex: (this.excludePageNum - 1) * this.excludePageSize,
        range: this.excludePageSize,
        isdroplistsearch: false,
        fixedcolumns: {
          STRATEGYID: this.pageMsgId
        }
      }
      const resultData = await this.sameGetItemFn(params);
      const { rows, total } = resultData || {};
      if (rows && rows.length) {
        rows.forEach((rowInfo, index) => {
          rowInfo["showIndex"] = (this.excludePageNum - 1) * this.excludePageSize + index + 1;//标记行号用于显示
          rowInfo["rowIndex"] = index;
          Object.keys(rowInfo).forEach((key) => {
            // 如果是排除商品类型,追加显示字段明细使用
            if (key == "DIMENSIONTYPE") {
              const tempVal = rowInfo[key].refobjval || "";
              // 下拉框列表
              const options = this.excludeProdForm.data.addcolums[0].childs[0].combobox || [];
              const filtOption = options.filter(op => op.limitval == tempVal)[0] || {};
              const { limitdesc } = filtOption || {};
              rowInfo["SHOW_DIMENSIONTYPE"] = tempVal ? limitdesc : '';//用于显示
            }
          });
        })
        this.excludeTotal = total || 0;
        this.excludeData = rows || [];
      } else {
        this.excludeTotal = 0;
        this.excludeData = [];
      }
    },
    // 排除商品明细保存
    async saveDetailHandle() {
      // 必填项校验
      const emptyMustItem = this.checkMustCellFn({checkType: "exclude_prod"});
      if (emptyMustItem) return;
      // 清空明细条件
      if (this.isRequesting) return;
      const data = {
        ID: -1,
        STRATEGYID: this.pageMsgId,
        DIMENSIONTYPE: this.excludeFormModel.DIMENSIONTYPE || "",
        DIMENSIONVALUE: this.excludeFormModel.DIMENSIONVALUE || "",
      }
      const excludeParam = {
        fixedData: {
          T_SKUPRICEEXCLUDEITEM: data,
        },
        objId: -1,
        table: 'T_SKUPRICEEXCLUDEITEM'
      }
      this.isRequesting = true;
      const resData = await this.sameSaveDetailFn(excludeParam);
      const { code, message } = resData || {};
      if (code == 0) {
        this.isRequesting = false;
        this.$Message.success('添加成功');
        this.mapSetFromModelFn({setType: 'exclude_prod' });
        this.getExcludeList()
      } else {
        this.isRequesting = false;
        this.$Message.error(message);
      }
    },
    DropShopvalueChange(value) {
      this.tabList[0].list[1].VALUE = '';
      if (value && value.length) {
        value.forEach(item=>{
          this.tabList[0].list[1].VALUE=this.tabList[0].list[1].VALUE==''?item.ID:this.tabList[0].list[1].VALUE+','+item.ID
        })
      }
    },
      postTableData(url, message, vm) {
        // 表格数据展示
        return new Promise((resolve) => {
          vm.post(url, message, (data) => {
            data.data.tabth.forEach(item => {
              if (item.display === 'iconfontpicker') {
                item.render = (h, params) => h('div', [
                  h('div', {
                    props: {//   type: 'primary',
                      size: 'small'
                    },
                    style: {
                      marginRight: '2px',
                      height: '15px',
                      width: '15px',
                      'background-color': JSON.parse(params.row[params.column.colname].val).color,
                    },
                  }),
                ]);
              }
            });
            resolve(data);
          });
        });
      },
    // 获取监控范围明显
    async getMonitorList() {
      const params = {
        table: 'T_IESSKUPRICESTRATEGYSCOPE',
        startindex: (this.monitorCurrentPage - 1) * this.monitorPageSize,
        range: this.monitorPageSize,
        isdroplistsearch: false,
        fixedcolumns: {
          STRATEGYID: this.pageMsgId
        }
      }
      const resultData = await this.sameGetItemFn(params);
      const { rows, total } = resultData || {};
      this.monitorTotalPage = total;
      this.monitorData = rows.map(item => {
        return {
          ...item,
          MONITORVALUE: (item.MONITORTYPE.refobjval === '1' || item.MONITORTYPE.refobjval === '3') && item.MONITORVALUE.val ? item.MONITORVALUE.val + '%' : item.MONITORVALUE.val
        }
      })
    },
    // 获取监控范围和排除商品公用
    async sameGetItemFn(reqParam) {
      const res = await network.post('/p/cs/list/query', reqParam);
      const resultData = res.data || {};
      return resultData;
    },

    // changeAlertType() {
    //   this.detailForm.MONITORVALUE = ''
    // },

    // 翻页
    onPageChange(val) {
      this.monitorCurrentPage = val
      this.getMonitorList()
    },

    // 每页条数
    onPageSize(val) {
      this.monitorPageSize = val
      this.monitorCurrentPage = 1
      this.getMonitorList()
    },

    // 添加监控数据
    async addMonitor() {
      if(!this.validateMonitor()) {
        return
      }
      if (this.isRequesting) return;
      console.log('新增', this.detailForm, this.pageMsgId)
      const data = {
        ID: -1,
        STRATEGYID: this.pageMsgId,
        BRANDID: this.detailForm.BRANDID,
        SEASON: this.detailForm.SEASON,
        YEAR: this.detailForm.YEAR,
        CATEGORY: this.detailForm.CATEGORY,
        MONITORTYPE: this.detailForm.MONITORTYPE,
        MONITORVALUE: this.detailForm.MONITORVALUE
      }
      this.clearMonitorForm()
      const monitorParam = {
        fixedData: {
          T_IESSKUPRICESTRATEGYSCOPE: data,
          // T_IESSKUPRICESTRATEGY: {
          //   ID: this.pageMsgId,
          //   NAME: baseMsg.list[0].VALUE,
          //   SHOPID: baseMsg.list[1].VALUE ? baseMsg.list[1].VALUE.join(',') : '',
          //   STARTDATE: this.startTime,
          //   ENDDATE: this.endTime,
          //   TYPE: baseMsg.list[3].VALUE,
          // }
        },
        objId: -1,
        table: 'T_IESSKUPRICESTRATEGYSCOPE'
      }
      this.isRequesting = true;
      const resData = await this.sameSaveDetailFn(monitorParam);
      const { code, message } = resData || {};
      if (code == 0) {
        this.isRequesting = false;
        this.$Message.success('添加成功');
        this.getMonitorList()
      } else {
        this.isRequesting = false;
        this.$Message.error(message);
      }
    },
    /**
     * 监控范围和排除商品公用接口
     */
    async sameSaveDetailFn(reqParam) {
      const res = await network.post('/p/cs/objectSave', reqParam);
      const resultData = res.data || {};
      return resultData;
    },
    // 监控范围明显勾选
    onSelectionChanged(val) {
      this._selectMonitorList = val.map(item => {
        return {
          ID: item.ID.val
        }
      })
    },

    // 删除监控数据
    deleteMonitor(option) {
      const { deleteType } = option || {};
      this.$Modal.fcWarning({
        title: '警告',
        mask: true,
        showCancel: true,
        content: '请确认是否删除？',
        onOk: () => {
          const deleteItems = {
            'monitor_area': {
              T_IESSKUPRICESTRATEGYSCOPE: this._selectMonitorList,
            },
            'exclude_prod': {
              T_SKUPRICEEXCLUDEITEM: this.checkedExcludeIds,
            }
          }
          const reqParam = {
            deleteType,//monitor_area监控区域和排除商品
            tableName: 'T_IESSKUPRICESTRATEGY',// 删除主表名称一样
            tabItem: deleteItems[deleteType],
          };
          this.sameDeleteFn(reqParam);
        }
      })
    },
    /**
     * 监控范围和排除商品 公用
     */
    async sameDeleteFn(option) {
      if (this.isRequesting) return;
      const { deleteType, tableName, tabItem } = option || {};
      const deleReq = {
        delMTable: false,
        objId: this.pageMsgId,
        table: tableName || '', // 主表
        tabItem: tabItem,
      }
      this.isRequesting = true;
      const res = await network.post('/p/cs/objectDelete', deleReq);
      const resultData = res.data || {};
      const { code, message } = resultData || {};
      if (code == 0) {
        this.isRequesting = false;
        this.$Message.success('删除成功');
        if (deleteType == 'monitor_area') {
          this.getMonitorList()
        } else if (deleteType == 'exclude_prod') {
          this.getExcludeList();
        }
      } else {
        this.isRequesting = false;
        this.$Message.error(message);
      }
    },

    // 监控范围和排除商品导入公用,type区分
    importHandle(option) {
      const { importType } = option || {};
      const tempInfos = {
        "monitor_area": {
          nameText: "监控范围",
          tableName: "T_IESSKUPRICESTRATEGYSCOPE",
        },
        "exclude_prod": {
          nameText: "排除商品",
          tableName: "T_SKUPRICEEXCLUDEITEM",
        }
      }
      const curItem = tempInfos[importType] || null;
      const { nameText, tableName } = curItem || {};
      if (tableName) {
        this.PriceMonitorDetailvisible = true;
        this.customImport = false;
        this.subTableName = nameText;
        this.subTable = tableName;
      }
    },
    /**
     * 监控范围和排除商品导出公用type区分
     */
    async exportHandle(option) {
      const { exportType } = option || {};
      const allInfos = {
        "monitor_area": {
          nameText: "监控范围",
          tableName: "T_IESSKUPRICESTRATEGYSCOPE",
        },
        "exclude_prod": {
          nameText: "排除商品",
          tableName: "T_SKUPRICEEXCLUDEITEM",
        }
      }
      if (this.isRequesting) return;
      const curInfo = allInfos[exportType] || null;
      const { nameText, tableName } = curInfo || {};
      if (tableName) {
        const exportParam = {
          searchdata: {
            table: tableName,
            startIndex: 0,
            fixedcolumns: {
              STRATEGYID: this.pageMsgId
            },
            column_include_uicontroller: true,
          },
          filename: nameText,
          filetype: '.xlsx',
          showColumnName: true,
          menu: nameText
        }
        this.isRequesting = true;
        const res = await network.post('/p/cs/export', urlSearchParams(exportParam))
        if(res.data.code === 0) {
          this.isRequesting = false;
          this.$Message.success({
            content: res.data.message,
            duration: 3
          })
        } else {
          this.isRequesting = false;
        }
      }
    },
    backToList() { // 返回策略列表页面
      let flag = true;
      console.log(this.oldBaseMsg.shopid)
      console.log(this.tabList[0].list[1].VALUE)
      for (let i = 0; i < this.tabList[0].list.length; i++) {
        if (this.oldBaseMsg.name != this.tabList[0].list[0].VALUE) {
          flag = false;
          break;
        } else if (this.oldBaseMsg.shopid != this.tabList[0].list[1].VALUE) {  //.join(',')
          flag = false;
          break;
        } else if (this.oldBaseMsg.startTime != this.startTime) {
          flag = false;
          break;
        } else if (this.oldBaseMsg.endTime != this.endTime) {
          flag = false;
          break;
        }
      }
      // if(this.currentReturnData.length > 0){
      //   flag = false
      // }
      if (!flag) {
        this.showTip = true;
      } else {
        this.closePage();
      }
    },
    getStategyDetail() { // 编辑页面获取策略详情
      let params = {
        id: this.pageMsgId
      }
      network.post('/p/cs/strategy/skuprice/detail', params).then(res => {
        if (res.data.code == 0) {
          this.tabList[0].list[0].VALUE = res.data.data.name
          // this.tabList[0].list[1].VALUE = ''
          let idArr = []
          let titleArr = [];
          res.data.data.shop_info_list.forEach((itemOne,index) => {
            idArr += (itemOne.shopid + (index==res.data.data.shop_info_list.length - 1?'':','))
            titleArr += (itemOne.shopname + (index==res.data.data.shop_info_list.length - 1?'':','))
          })
          let idArrs = idArr.split(',')
          let titleArrs = titleArr.split(',')
          this.dropDownShopValue=(idArrs).map((item,i) => ({ID:item, Label: titleArrs[i]}));
          this.tabList[0].list[1].VALUE = idArr
          this.tabList[0].list[2].VALUE = [res.data.data.startdate, res.data.data.enddate]
          this.startTime = res.data.data.startdate
          this.endTime = res.data.data.enddate
          this.tabList[0].list[3].VALUE = String(res.data.data.type)
          this.oldBaseMsg = {
            name: res.data.data.name, // 策略名称
            shopid: idArr, // 店铺
            startTime: res.data.data.startdate, // 开始时间
            endTime: res.data.data.enddate, // 结束时间
            type: res.data.data.type, // 策略类型
          }
          this.panelFormData.data.addcolums[0].childs[0].valuedata = String(res.data.data.type)
          this.syncpltstock = String(res.data.data.syncpltstock) // 触发预警价格自动将平台库存置0
          this.panelFormData.data.addcolums[0].childs[1].valuedata = this.syncpltstock
          // 接收人回填数据
          const contacts = res.data.data.contacts || []
          this.contacts = contacts.map(item => item.id)
          if(contacts.length > 0){
            this.panelFormData.data.addcolums[0].childs[2].refobjid = contacts.map(item => item.id).join(',')
            this.panelFormData.data.addcolums[0].childs[2].valuedata = contacts.map(item => item.NAME).join(',')
          }
          
          console.log("🚀 ~ 值", this.panelFormData.data.addcolums[0].childs[0], this.contacts)
        }
      })
    },
    getpageDetailList(type) {
      let params = {
        id: this.pageMsgId,
        page: this.returnCurrentPage,
        pageSize: this.pageSizeReturn,
        dimensiontype: this.MonitoreDimensionType,
        searchVal: this.MonitoreDimensionMsg
      }
      network.post('/p/cs/strategy/skuprice/page/items', params).then(res => {
        if (res.data.code == 0) {
          let currentPageData = [];
          if (type == 'table') {
            this.returnData = [];
          }
          if (res.data.data.resultList.length > 0) {
            res.data.data.resultList.forEach(item => {
              let obj = {};
              if (item.dimensiontype != 1) {
                obj = {
                  id: item.id,
                  PriceMonitoreDimension: Number(item.dimensiontype),
                  MonitorDimensionValue: String(item.dimensionvalue2),
                  MonitorDimensionValueID: Number(item.dimensionvalue2),
                  MonitoreType: Number(item.monitortype),
                  MonitorSetValue: String(item.monitorvalue),
                  MonitorDimensionList: { // 表格数据的监控维度值
                    VALUE: String(item.dimensionvalue2), //字段值
                    clearable: true,
                    tableName: 'T_IESBRAND',//表名
                    currentIndex: 0,//当前页码
                    dataEmptyMessage: '数据加载中...', // 无数据的提示
                    columns: ['name', 'value'],// 展现的组
                    AutoData: [],//模糊搜索
                    defaultSelected: [{ "ID": String(item.dimensionvalue2), "Label": String(item.dimensionvalue) }],//默认数据
                    shopData: {},
                  }
                }
              } else {
                obj = {
                  id: item.id,
                  PriceMonitoreDimension: Number(item.dimensiontype),
                  MonitorDimensionValue: String(item.dimensionvalue),
                  MonitorDimensionValueID: Number(item.dimensionvalue),
                  MonitoreType: Number(item.monitortype),
                  MonitorSetValue: String(item.monitorvalue),
                  MonitorDimensionList: { // 表格数据的监控维度值
                    VALUE: String(item.dimensionvalue2), //字段值
                    clearable: true,
                    tableName: 'T_IESBRAND',//表名
                    currentIndex: 0,//当前页码
                    dataEmptyMessage: '数据加载中...', // 无数据的提示
                    columns: ['name', 'value'],// 展现的组
                    AutoData: [],//模糊搜索
                    defaultSelected: [{ "ID": String(item.dimensionvalue), "Label": String(item.dimensionvalue2) }],//默认数据
                    shopData: {},
                  }
                }
              }
              currentPageData.push(obj);
              if (this.returnData.length < res.data.data.total) {
                this.returnData.push(obj);
              }
            })
          }
          this.totalReturn = res.data.data.total
          // 截取数组
          // let startIndex=this.pageSizeReturn*(this.returnCurrentPage-1)
          // let endIndex=startIndex+this.pageSizeReturn
          // this.returnData.slice(startIndex,endIndex)
          this.currentReturnData = currentPageData //当前页面显示明细
        }
      })
    },
    rangeDate(e) {
      this.startTime = e[0];
      this.endTime = e[1];
    },
    limitStartDate(e) {
      this.limitStartDate = e
    },
    limitEndDate(e) {
      this.limitEndDate = e
    },
    // 重置数据
    resetData() {
      this.tabList.forEach(item => {
        item.list.forEach(i => {
          if (i.TYPEONE == 'checkbox') {
            i.VALUE = false
          } else {
            i.VALUE = ''
          }
        })
      })
      this.tabName = 'name1';
      this.showDetailTable = true;
      this.returnData = []; // 策略明细置空
      this.currentReturnData = []; // 策略明细置空

      // 策略明细搜索栏重置
      if (this.$refs.returnSelect) {
        this.detail = {
          PriceMonitoreDimension: '', // 监控维度
          MonitorDimensionValue: '', // 监控维度值
          MonitoreType: '', // 监控类型
          MonitorSetValue: '', // 监控设置值
        }
        // this.$refs.returnSelect.clearSingleSelect()
      }
    },
    // 关闭当前页面
    closePage() {
      const { fullPath } = this.$route;
      const {
        keepAliveModuleName, tableName
      } = this.$store.state.global.activeTab;
      this.$store.commit('global/tabCloseAppoint', {
        tableName,
        routeFullPath: fullPath,
        keepAliveModuleName,
        stopRouterPush: true,
      });
      // 跳转
      setTimeout(() => {
        R3.store.commit('global/tabOpen', {
          type: 'S',
          tableName: 'T_IESSKUPRICESTRATEGY',
          tableId: '11475',
          back: true
        });
      }, 0)
    },

    // 获取监控维度值
    // 外键下拉框
    searchShopData(params, type) {
      let virtual = {}
      if (this.detail.PriceMonitoreDimension == '1' || (type == 'table' && params.row.PriceMonitoreDimension == '1')) { // 商品品牌
        virtual = {
          searchdata: {
            "isdroplistsearch": true,
            "refcolid": 202944,
            "startindex": type !== 'table' ? this.MonitorDimensionValue.currentIndex : params.row.MonitorDimensionList.currentIndex,
            "range": 10,
            "fixedcolumns": {},
          }
        }
      } else if (this.detail.PriceMonitoreDimension == '2' || (type == 'table' && params.row.PriceMonitoreDimension == '2')) { // 商品编码
        virtual = {
          searchdata: {
            "isdroplistsearch": true,
            "refcolid": 202940,
            "startindex": type !== 'table' ? this.MonitorDimensionValue.currentIndex : params.row.MonitorDimensionList.currentIndex,
            "range": 10,
            "fixedcolumns": {},
            "fkdrplist": {
              searchcols: ["PRODUCTCODE"]
            },
          }
        }
      } else if (this.detail.PriceMonitoreDimension == '3' || (type == 'table' && params.row.PriceMonitoreDimension == '3')) { // 商品编码
        virtual = {
          searchdata: {
            "isdroplistsearch": true,
            "refcolid": 202943,
            "startindex": type !== 'table' ? this.MonitorDimensionValue.currentIndex : params.row.MonitorDimensionList.currentIndex,
            "range": 10,
            "fixedcolumns": {},
          }
        }
      }
      network.post('/p/cs/QueryList', urlSearchParams(virtual)).then((res) => {
        if (res.data.code == 0) {
          if (type == 'table') {
            params.row.MonitorDimensionList.shopData = res.data.data
            params.row.MonitorDimensionList.currentIndex = 0
          } else {
            this.MonitorDimensionValue.shopData = res.data.data
            this.MonitorDimensionValue.currentIndex = 0
          }
        }
      })
    },
    // 单选下拉选中
    checkDataShop(val, params, type) {
      if (type == 'table') {
        params.row.MonitorDimensionList.VALUE = val[0].ID
        params.row.MonitorDimensionList.NAME = val[0].Label
      } else {
        this.MonitorDimensionValue.VALUE = val[0].ID
        this.MonitorDimensionValue.NAME = val[0].Label
      }
    },
    // 单选框失去焦点事件
    changeDataShop(e, params, type) {
      if (!e.target.value) {
        if (type == 'table') {
          params.row.MonitorDimensionList.VALUE = ''
          params.row.MonitorDimensionList.NAME = ''
        } else {
          this.MonitorDimensionValue.VALUE = ''
          this.MonitorDimensionValue.NAME = ''
        }
      } else {
        if (type == 'table') {
          if (params.row.MonitorDimensionList.AutoData.length) {
            params.row.MonitorDimensionList.AutoData.forEach(v => {
              if (e.target.value == v.value) {
                params.row.MonitorDimensionList.VALUE = v.id
                params.row.MonitorDimensionList.NAME = v.value
              }
            })
          }
          e.target.value = params.row.MonitorDimensionList.NAME ? params.row.MonitorDimensionList.NAME : ''
        } else {
          if (this.MonitorDimensionValue.AutoData.length) {
            this.MonitorDimensionValue.AutoData.forEach(v => {
              if (e.target.value == v.value) {
                this.MonitorDimensionValue.VALUE = v.id
                this.MonitorDimensionValue.NAME = v.value
              }
            })
          }
          e.target.value = this.MonitorDimensionValue.NAME ? this.MonitorDimensionValue.NAME : ''
        }
      }
    },
    // 清空选中项
    clearDataShop(params, type) {
      if (type == 'table') {
        params.row.MonitorDimensionList.VALUE = ''
        params.row.MonitorDimensionList.NAME = ''
      } else {
        this.MonitorDimensionValue.VALUE = ''
        this.MonitorDimensionValue.NAME = ''
      }
    },
    // 单选下拉分页改变
    changePageShop(e, params, type) {
      if (type == 'table') {
        params.row.MonitorDimensionList.currentIndex = (e - 1) * 10
        this.searchShopData(params, type)
      } else {
        this.MonitorDimensionValue.currentIndex = (e - 1) * 10
        this.searchShopData()
      }
    },
    focusInputValueChangeShop(e, params, type) {
      let virtual = {}
      if (this.detail.PriceMonitoreDimension == '1' || (type == 'table' && params.row.PriceMonitoreDimension == '1')) { // 商品品牌
        virtual = {
          ak: e.target.value,
          colid: 202944,
          fixedcolumns: {}
        }
      } else if (this.detail.PriceMonitoreDimension == '2' || (type == 'table' && params.row.PriceMonitoreDimension == '2')) { // 商品编码
        virtual = {
          ak: e.target.value,
          colid: 202940,
          fixedcolumns: {},
        }
      } else if (this.detail.PriceMonitoreDimension == '3' || (type == 'table' && params.row.PriceMonitoreDimension == '3')) { // 商品条码
        virtual = {
          ak: e.target.value,
          colid: 202943,
          fixedcolumns: {},
        }
      }
      network.post('/p/cs/fuzzyquerybyak', urlSearchParams(virtual)).then((res) => {
        if (res.data.code == 0) {
          if (type == 'table') {
            params.row.MonitorDimensionList.AutoData = res.data.data
          } else {
            this.MonitorDimensionValue.AutoData = res.data.data
          }
        }
      })
    },
    // 单选下拉模糊搜索数据
    InputValueChangeShop(e, params, type) {
      let virtual = {}
      if (this.detail.PriceMonitoreDimension == '1' || (type == 'table' && params.row.PriceMonitoreDimension == '1')) { // 商品品牌
        virtual = {
          ak: e,
          colid: 202944,
          fixedcolumns: {}
        }
      } else if (this.detail.PriceMonitoreDimension == '2' || (type == 'table' && params.row.PriceMonitoreDimension == '2')) { // 商品编码
        virtual = {
          ak: e,
          colid: 202940,
          fixedcolumns: {},
        }
      } else if (this.detail.PriceMonitoreDimension == '3' || (type == 'table' && params.row.PriceMonitoreDimension == '3')) { // 商品条码
        virtual = {
          ak: e,
          colid: 202943,
          fixedcolumns: {},
        }
      }
      network.post('/p/cs/fuzzyquerybyak', urlSearchParams(virtual)).then((res) => {
        if (res.data.code == 0) {
          if (type == 'table') {
            params.row.MonitorDimensionList.AutoData = res.data.data
          } else {
            this.MonitorDimensionValue.AutoData = res.data.data
          }
        }
      })
    },


    // 店铺下拉气泡打开时
    searchTrueShopData(){
      let virtual={
        searchdata:{
          "isdroplistsearch":true,
          "refcolid":194851,
          "startindex":this.shopTrue.currentIndex,
          "range":10,
        }
      }
      network.post('/p/cs/QueryList',urlSearchParams(virtual)).then((res) => {
        if(res.data.code==0){
          this.shopTrue.shopData=res.data.data
          this.shopTrue.currentIndex=0
        }         
      })
    },
    // 店铺分页改变
    changePageTrueShop(val){
      this.shopTrue.currentIndex=(val-1)*10
      this.searchTrueShopData()
    },
    // 模糊搜索店铺数据
    InputValueChangeTrueShop(val){
      let virtual={
        ak: val,
        colid: 194851,
        fixedcolumns: {}
      }
      network.post('/p/cs/fuzzyquerybyak',urlSearchParams(virtual)).then((res) => {
        if(res.data.code==0){
          this.shopTrue.AutoDataShop=res.data.data  
        }        
      })
    },
    // 选中店铺项 拼接数据
    checkDataTrueShop(val){
      this.tabList[0].list[1].VALUE=''
      val.forEach(item=>{
          this.tabList[0].list[1].VALUE=this.tabList[0].list[1].VALUE==''?item.ID:this.tabList[0].list[1].VALUE+','+item.ID
      })
    },
    // 清空选中店铺项
    clearTrueShop(){
      this.tabList[0].list[1].VALUE=''
    },

    // 监控维度option选中
    selectPriceMonitoreDimension(val) {
      this.MonitorDimensionValue.VALUE = ''
      this.MonitorDimensionValue.NAME = ''
      this.MonitorDimensionValue.defaultSelected = []//默认数据
    },
    // 监控类型option选中
    selectMonitoreType(val) {
      if (val == '1') {
        this.MonitorSetValueContent = '根据商品成交单价/平台售价和预警折扣做比对'
      } else if (val == '2') {
        this.MonitorSetValueContent = '根据商品成交单价和预警成交单价做比对'
      }
      this.detail.MonitorSetValue = '';
    },

    // 添加策略明细到表格
    addReturnGoods() {
      if (this.detail.PriceMonitoreDimension == '') {
        this.$Message.warning('监控维度不能为空');
        return
      } else if (this.MonitorDimensionValue.VALUE == '') {
        this.$Message.warning('监控维度值不能为空');
        return
      } else if (this.detail.MonitoreType == '') {
        this.$Message.warning('监控类型不能为空');
        return
      } else if (this.detail.MonitorSetValue == '') {
        this.$Message.warning('监控设置值不能为空');
        return
      } else {
        this.$Modal.fcWarning({
          title: '警告',
          mask: true,
          showCancel: true,
          content: '添加操作数据库数据会同时发生变化，是否确认添加？',
          onOk: () => {
            let obj = {
              dimensiontype: this.detail.PriceMonitoreDimension,
              dimensionvalue: this.detail.PriceMonitoreDimension == 1 ? this.MonitorDimensionValue.VALUE : this.MonitorDimensionValue.NAME, // VALUE
              monitortype: this.detail.MonitoreType,
              monitorvalue: this.detail.MonitorSetValue,
            }
            let params = {
              id: this.pageMsgId,
              items: [obj]
            }
            network.post('/p/cs/strategy/skuprice/item/add', params).then(res => {
              if (res.data.code == 0) {
                this.detail = {
                  PriceMonitoreDimension: '', // 监控维度
                  MonitorDimensionValue: '', // 监控维度值
                  MonitoreType: '', // 监控类型
                  MonitorSetValue: '', // 监控设置值
                },
                  this.$Message.success('添加明细成功！')
                this.getpageDetailList('table');
              }
            })
          }
        })
      }
    },
    //初始查询标准下拉框数据
    getQuery(tableName, fixed) {
      let virtual = {
        fixedcolumns: fixed ? fixed : {},
        range: 2000,
        startindex: 0,
        table: tableName
      }
      if (tableName == 'T_V_IESSHOP') {
        virtual.isdroplistsearch = true
      }
      network.post('/p/cs/list/query', virtual).then((res) => {
        this.tabList[0].list.forEach(item => {
          if (item.ID == tableName) {
            if (tableName == 'T_V_IESSHOP') {
              item.optionList = res.data.rows.map(i => {
                return {
                  label: i.SHOPTITLE.val,
                  value: i.ID.val
                }
              })
            } else {
              item.optionList = res.data.rows.map(i => {
                return {
                  label: i.NAME.val,
                  value: i.ID.val
                }
              })
            }
          }
        })
      })
    },

    // 策略明细表删除
    deleteReturnGoods() {
      this.$Modal.fcWarning({
        title: '警告',
        mask: true,
        showCancel: true,
        content: '删除操作数据库数据会同时被清除，是否确认删除？',
        onOk: () => {
          let idArray = this.submitArrReturn.map(item => item.id)
          let params = {
            ids: idArray
          }
          network.post('/p/cs/strategy/skuprice/item/del', params).then(res => {
            if (res.data.code == 0) {
              this.$Message.success('删除明细成功！');
              this.getpageDetailList('table');
            }
          })
        }
      })

    },

    // 策略明细页码改变时触发
    changePageReturn(val) {
      // 1=>0 2=>10 3=>20
      this.returnCurrentPage = val
      this.getpageDetailList();
      // 截取数组
      let startIndex = this.pageSizeReturn * (this.returnCurrentPage - 1)
      let endIndex = startIndex + this.pageSizeReturn
      this.currentReturnData = this.returnData.slice(startIndex, endIndex)
    },
    // 策略明细页数改变时触发
    changeSizeReturn(val) {
      this.pageSizeReturn = val;
      this.returnCurrentPage = 1;
      // this.currentReturnPage = 0;
      // 截取数组
      let startIndex = this.pageSizeReturn * (this.returnCurrentPage - 1)
      let endIndex = startIndex + this.pageSizeReturn
      this.currentReturnData = this.returnData.slice(startIndex, endIndex)
    },
    // 策略明细表格选中某项时触发
    selectReturnData(selection, row) {
      this.submitArrReturn = selection;
    },
    // 策略明细表格取消某项时触发
    selectReturnCancel(selection, row) {
      this.submitArrReturn = selection;
    },
    // 策略明细表格全选
    selectReturnDataAll(selection) {
      this.submitArrReturn = selection;
    },
    // 策略明细表格取消全选
    selectReturnDataCancel(selection) {
      this.submitArrReturn = selection;
    },

    parser(value) {
      if ((typeof value == 'string')) {
        return parseFloat(value.replace(/[^\d\.-]/g, ''));
      } else {
        return value
      }

    },

    checkInputSKU(e, i) {
      if (i.SKEY == 'activegoodstype') {
        if (e == '限制商品') {
          this.tabName = 'name2'
        } else if (e == '排除商品') {
          this.tabName = 'name3'
        } else {
          this.tabName = 'name1'
        }
      } else if (i.SKEY == 'gift_method') {
        if (e == '随机分组赠送') {
          if (!this.tabList[1].list[3].VALUE) {
            this.tabList[1].list[3].VALUE = true;
          }
          this.tabList[1].list[3].disabled = true;
        } else {
          this.tabList[1].list[3].disabled = false;
        }
      } else {
        let tableName = i.ID
        if (tableName == 'T_V_IESSHOP') {
          this.getQuery(tableName, { SHOPTITLE: e })
        }
      }
    },
    // 平台单号，退款单号(换货单没有)，退回物流单号禁止输入空格
    noSpaces(e, i) {
      if (i.SKEY == 'satisfied_amount' || i.SKEY == 'satisfied_pieces') {
        if (e.keyCode == 32) e.returnValue = false
      }
    },
    // 保存
    saveAll() {
      let baseMsg = this.tabList[0]; //基本设置
      if (!baseMsg.list[0].VALUE) {
        return this.$Message.warning('策略名称不能为空！');
      }
      if (!baseMsg.list[1].VALUE) {
        return this.$Message.warning('使用店铺不能为空！');
      }
      if (!this.startTime || !this.endTime) {
        return this.$Message.warning('起止时间不能为空！');
      }
      if ((new Date(this.endTime).getTime()) < (new Date().getTime())) {
        return this.$Message.warning('结束时间必须大于当前系统时间！');
      }
      if (!baseMsg.list[3].VALUE) {
        return this.$Message.warning('策略类型不能为空！');
      }
      // if(!this.returnData.length){
      //   return this.$Message.warning('明细不能为空！');
      // }

      // 策略明细
      let DIMENSIONLIST = []
      this.returnData.forEach(item => {
        let obj = {
          'id': item.id,
          "dimensiontype": item.PriceMonitoreDimension,
          "dimensionvalue": item.PriceMonitoreDimension == 1 ? item.MonitorDimensionValue : item.MonitorDimensionList.defaultSelected[0].Label,
          "monitortype": item.MonitoreType,
          "monitorvalue": item.MonitorSetValue,
        }
        DIMENSIONLIST.push(obj)
      })
      let params = { // 保存接口参数
        id: this.pageMsgId,
        name: baseMsg.list[0].VALUE,
        shopid: baseMsg.list[1].VALUE ? baseMsg.list[1].VALUE : '',  //.join(',')
        startdate: this.startTime,
        enddate: this.endTime,
        type: baseMsg.list[3].VALUE,
        items: DIMENSIONLIST,
        syncpltstock: Number(this.syncpltstock),
        userids: this.contacts,
      }
      this.saveSubmit(params)
    },
    saveSubmit(params) {
      network.post('/p/cs/strategy/skuprice/edit', params).then(res => {
        if (res.data.code == 0) {
          this.$Message.success('修改策略成功！');
          this.closePage();
        }
      })
    },
    // 策略明细表导入
    importStrategyDetailExcel() {
      this.PriceMonitorDetailvisible = true;
      this.customImport = true
      this.subTableName = '策略明细'
      this.subTable = 'T_IESSKUPRICESTRATEGYITEM'
    },

    // 策略明细表导出
    async exportStrategyDetailExcel() {
      let userId = JSON.parse(localStorage.getItem('userInfo')).id;
      let data = await network.get(`/p/cs/judge/export_the_verification_code?tableName='T_IESSKUPRICESTRATEGYITEM'`);
      if (data.data.data) {
        let virtual = {
          table: 'V_USERS', // USERS
          objid: userId,
        };
        this.$network.post('/p/cs/object/query', virtual).then((res) => {
          let str = res.data.MOBIL;
          let a = /^1\d{10}$/;
          if (str && a.test(str)) {
            let MOBIL = str;
            let refresh = this.searchClickData;
            this.$R3Dialog({
              dialogComponentName: 'exportValidate', // 自定义的弹框组件
              title: '导出校验', // 弹框标题
              footerHide: true,
              externalOptions: {
                massage: MOBIL,
                refresh
              }
            }, () => {
              this.batchExport(event); // 调用框架导出
            });
          } else {
            this.$Modal.fcError({
              title: '错误',
              content: '当前用户手机号为空或格式不正确，请联系管理员在【用户档案】中进行修改',
              mask: true,
            });
          }
        });
      }else {
        this.batchExport(event); // 调用框架导出
      }
    },
    batchExport() {
      let searchdata = { "table": "T_IESSKUPRICESTRATEGYITEM", "startIndex": 0, "fixedcolumns": {}, "range": 1000, "column_include_uicontroller": true }
      let fd = new FormData();
      fd.append('strategyId', this.pageMsgId);
      network.post('/p/cs/strategy/skuprice/item/export', fd).then(res => {
        if (res.data.code == 0) {
          this.$Modal.fcSuccess({
            title: '成功',
            mask: true,
            content: res.data.message
          });
          const asyncTaskScheme = () => (window.ProjectConfig && window.ProjectConfig.asyncTaskScheme ? window.ProjectConfig.asyncTaskScheme : '');  // 异步导出设计方案
          if(asyncTaskScheme() === 'skq') {
            const params = {
              detail: {
                type: 'notice'
              }
            }
            DispatchEvent(R3_IMPORT, params)
            this.$R3loading.hide(this.loadingName);
            // this.closeDialog()
            return
          }
        }
      })
    },

    // 策略明细表导入弹框关闭
    closeActionDialog() {
      this.PriceMonitorDetailvisible = false;
    },
  }
};
</script>
<style lang="less">
.quickOperation {
  height: 64px;
  border-bottom: 1px solid #d8d8d8;
  display: flex;
  align-items: center;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #333333;
}
.content {
  .block {
    padding-top: 24px;
  }
  .ark-col {
    display: flex;
    align-items: center;
    // justify-content: flex-end;
    margin-bottom: 16px;
    .input_box {
      max-width: 400px;
      min-width: 180px;
    }

    .ark-input-wrapper /deep/ textarea {
      resize: none;
      min-height: 36px !important;
    }
    .title {
      min-width: 80px;
      display: flex;
      justify-content: flex-end;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #575757;
      display: flex;
      align-items: center;
      margin-right: 4px;
      img {
        margin-left: 5px;
        width: 16px;
      }
    }
  }
}
.refund-content {
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  align-items: center;

  .count-part {
    height: 60px;
    margin-bottom: 16px;
    border-bottom: 1px solid #d8d8d8;
    .item {
      display: flex;
      align-items: center;
      .text {
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #333333;
      }
    }
    .img-framelanflag {
      cursor: pointer;
      vertical-align: middle;
      margin-top: -3px;
      margin-left: 5px;
      width: 16px;
    }
    .input-money {
      width: 80px;
      margin: 0 8px;
    }
    .plus {
      margin: 0 16px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #979797;
    }
  }
  .total-part {
    display: flex;
    align-items: center;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #333333;
  }
}

.AbnormalPriceMonitoreStrategy .ark-upload-drag {
  border: none;
}
.AbnormalPriceMonitoreStrategy
  .ark-select-multiple
  .ark-select-item.ark-select-item-all {
  display: none;
}
.priceMonitor .img-framelanflag {
  cursor: pointer;
  vertical-align: middle;
  margin-top: 0px;
  margin-left: 0px;
  width: 16px;
}
.AbnormalPriceMonitoreStrategy .priceMonitor .input_box.ark-fkrp-select {
  width: 220px;
}
.AbnormalPriceMonitoreStrategy .shopDropMultiSelectFilter {
  width:100%;
}
</style>
<style lang="less" scoped>
.AbnormalPriceMonitoreStrategy {
  min-width: 1380px;
}
.pageContent {
  margin-top: 12px;
  display: flex;
  justify-content: flex-end;
}
.order-setting-input-error:before {
  content: '*';
  color: red;
}
.conditionContent,
.conditionContentOne {
  width: 100%;
  display: flex;
  max-height: 3000px;
  overflow: hidden;
  flex-wrap: wrap;
  padding-top: 8px;
  justify-content: space-between;
  .itemContent {
    width: calc((100% - 120px) / 3);
    display: flex;
    align-items: center;
    margin: 0 20px 24px;
    .itemLabel {
      min-width: 84px;
      font-size: 12px;
      font-weight: 500;
      color: #4c4c4c;
      line-height: 17px;
      margin-right: 8px;
      text-align: right;
    }
    .posterType {
      width: calc(100% - 84px);
    }
  }
}
.tableArea /deep/ .ark-tabs-bar {
  margin-bottom: 0px;
  .ark-tabs-tab {
    line-height: 22px !important;
  }
}
.tableArea {
  padding-top: 24px;
  .handleBtn {
    height: 16px;
    margin-bottom: 16px;
    display: flex;
    // justify-content: space-between;
    align-items: center;
    position: relative;
    .handleItem {
      width: 48px;
      height: 16px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: var(--primary-color);
      line-height: 16px;
      margin: 0 2px;
      cursor: pointer;
    }
    .searchList {
      position: absolute;
      right: 0;
    }
  }
}
.content /deep/ .ark-select-input[disabled] {
  color: #575757;
}

.strategy-panel {
  width: 100%;
  /deep/.ark-collapse-item {
    padding: 0;
  }
  /deep/.ark-collapse > .ark-collapse-item > .ark-collapse-content {
    padding: 0;
  }
}

.form-item {
  display: flex;
  align-items: center;
  .form-label {
    margin-right: 4px;
  }
  .value-width {
    width: 166px !important;
  }
}
/deep/ #syncpltstock .ItemComponentRoot .itemLabel{
  flex: 0 0 210px!important;
}
</style>
