<template>
  <div class="app-container">
    <card-table :modal-data="tableData" :searchParams="queryParams" @pagination="getList" :loading="loading"
      :tableSearch="true" @columnSearch="handleQuery" @resetList="resetQuery" @selection-change="handleSelectionChange">
      <template #operations="{ selections }">
        <Row :gutter="20">
          <el-col :span="1.5">
            <CustomButton icon="el-icon-plus" type="primary" size="mini" label="validation.addRule" @handleClick="toAdd" />
            <CustomButton icon="el-icon-document-add" size="mini" plain  label="追加关联梯型" @handleClick="handleRelateElevator(true)" />
            <CustomButton icon="el-icon-delete" size="mini" plain label="删除关联梯型" @handleClick="handleRelateElevator(false)" />
            <CustomButton icon="el-icon-download" size="mini" plain label="导出" @handleClick="handleExport" :loading="exportLoading"/>
            <ImportModal style="margin-left:10px" title="导入" icon="el-icon-upload2" :close="getList" :tableType="8" />
          </el-col>
        </Row>
      </template>

      <Column type="index" label="No" />
      <Column type="selection" align="center" />
      <!--      规则名称-->
      <Column :label="$t('validation.ruleName')" prop="caseName" :searchParams="queryParams" :showSearch="true" />
      <Column :label="$t('validation.formulaSetting')" prop="conditionFormula" />
      <Column :label="$t('是否用于报价')" align="center" prop="quotationFlag" :min-width="150"
                :searchDict="dict.type.yes_no_tinyint" :searchParams="queryParams" :showSearch="true" searchType="select">
          <template #default="{ row }">
            <span>{{ formatDict(row.quotationFlag,'yes_no_tinyint') }}</span>
          </template>
        </Column>
        <Column :label="$t('是否用于土建')" align="center" prop="civilFlag" :min-width="150"
                :searchDict="dict.type.yes_no_tinyint" :searchParams="queryParams" :showSearch="true" searchType="select">
          <template #default="{ row }">
            <span>{{ formatDict(row.civilFlag,'yes_no_tinyint') }}</span>
          </template>
        </Column>
      <Column :label="$t('validation.status')" prop="status" :min-width="80" :showSearch="true" searchType="select" :searchParams="queryParams" :searchDict="dict.type.status_switch">
        <template #default="{ row }">
          <el-switch v-model="row.status" :active-value="'0'" :inactive-value="'1'"
            @change="val => handleRowStatus(val, row)" />
        </template>
      </Column>

      <Column label="关联梯型" align="center" prop="relatedModelIds" :min-width="200" :selectMore="true"
        :searchParams="queryParams" :searchDict="relatedModelList" :showSearch="true" searchType="select">
        <template #default="{ row }">
          <span>{{ row.relatedModel }}</span>
        </template>
      </Column>
      <Column :label="$t('validation.updateBy')" prop="updateByName" :min-width="80"  :searchParams="queryParams" :showSearch="true"/>
      <Column :label="$t('validation.updateTime')" prop="updateTime" :searchParams="queryParams"
      :showSearch="true" searchType="dateRange"/>
      <!--      <Column :label="$t('validation.createBy')" prop="createByName" :min-width="80"/>-->
      <!--      <Column :label="$t('validation.createTime')"  :min-width="200" :searchParams="queryParams"-->
      <!--              :showSearch="true" searchType="dateRange">-->
      <!--        <template #default="{row}">-->
      <!--           {{parseTime(row.createTime) }}-->
      <!--        </template>-->
      <!--      </Column>-->
      <Column :label="$t('common.operate')" :showSearch="true" search-type="operate" :min-width="250">
        <template #default="{row}">
          <CustomLink label="common.view" @handleClick="toView(row)" icon="el-icon-view" size="mini" style="font-size: 12px"/>
          <CustomLink label="validation.seeElevator" @handleClick="toViewElevator(row)" icon="el-icon-check" size="mini" style="font-size: 12px"/>
          <el-dropdown size="mini"  @command="(command) => handleCommand(command, row)">
            <el-button icon="el-icon-d-arrow-right" size="mini" type="text">{{ $t('common.more') }}</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item  command="toEdit"
                                 size="mini" icon="el-icon-edit">{{ $t('common.edit') }}
              </el-dropdown-item>

              <el-dropdown-item  command="deleteRow"
                                 size="mini" icon="el-icon-delete">{{ $t('common.delete') }}
              </el-dropdown-item>

<!--              <CustomLink label="common.edit" @handleClick="toEdit(row)"/>-->
<!--              <CustomLink label="common.delete" @handleClick="deleteRow(row)"/>-->
            </el-dropdown-menu>
          </el-dropdown>

        </template>
      </Column>


    </card-table>

    <Dialog ref="seeElevator" :title="$t('validation.seeElevator')" @close="dialogParams={  pageNum: 1,
        pageSize: 10,},dialogModalData=[]">
      <CardTable :modal-data="dialogModalData" :searchParams="dialogParams" @pagination="getDialogList"
                 :loading="dialogModalLoading" style="box-shadow: unset">
        <Column type="index" label="No"/>
        <Column :label="$t('elevatorModel.areaName')" prop="areaName"/>
        <Column label="区域（英）" prop="areaNameES"/>
        <Column label="区域（俄）" prop="areaNameRU"/>
        <Column label="区域（西）" prop="areaNameUS"/>
        <Column :label="$t('elevatorModel.elevatorModel')" prop="elevatorModel"/>
      </CardTable>
    </Dialog>

    <Dialog ref="suitModelDialog" title="适用电梯选择" maxWidth="1300px" @confirm="handleConfirm" @close="elevatorQueryParams = {
      pageNum: 1,
      pageSize: 10,
    }">
      <CardTable :modal-data="elevatorDialogModalData" :searchParams="elevatorQueryParams" @pagination="getElevatorList"
        :loading="elevatorLoading" :tableSearch="true" @columnSearch="handleElevatorQuery" style="box-shadow: unset"
        @resetList="resetElevatorQuery" @selection-change="elevatorSelectionChange">
        <Column type="selection" />
        <Column type="index" label="No" />
        <Column :label="$t('elevatorModel.areaName')" prop="areaName" :show-search="true"
          :searchParams="elevatorQueryParams" />
        <Column :label="$t('validation.areaUS')" prop="areaNameES" :show-search="true"
          :searchParams="elevatorQueryParams" />
        <Column :label="$t('validation.areaRU')" prop="areaNameRU" :show-search="true"
          :searchParams="elevatorQueryParams" />
        <Column :label="$t('validation.areaES')" prop="areaNameUS" :show-search="true"
          :searchParams="elevatorQueryParams" />
        <Column :label="$t('elevatorModel.elevatorModel')" prop="elevatorModel" :show-search="true" />
        <Column :label="$t('common.operate')" :min-width="200" :showSearch="true" align="center" fixed="right"
          search-type="operate" width="250px">
        </Column>
      </CardTable>
    </Dialog>


  </div>
</template>

<script>

import CardTable from "../../../components/element/table/CardTable.vue";
import Row from "../../../components/CustomElement/layout/Row.vue";
import Col from "../../../components/CustomElement/layout/Col.vue";
import CustomButton from "../../../components/CustomElement/CustomButton.vue";
import Column from "../../../components/element/table/Column.vue";
import { downloadTemplate } from '@/api/excel'
import moment from "moment";
import {
  changeValidationStatus,
  deleteValidation,
  getRelationByIdValidation,
  listValidation, batchChangeRelation
} from "../../../api/business/crm/paraValidation/paraValidation";
import CustomLink from "../../../components/CustomElement/CustomLink.vue";
import { parseTime } from "../../../utils/dateUtils";
import { listForComponents } from "@/api/business/crm/elevatorModel";
import { getRelatedModelList } from "@/api/business/crm/parabar/parabar.js";
import ImportModal from "../../../components/ImportModal/index";

export default {
  name: "ValidationConfig",
  components: { CustomLink, Column, CustomButton, Col, Row, CardTable, ImportModal },
  dicts: ['yes_no_tinyint', 'status_switch'],
  data() {
    return {
      tableData: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      loading: false,
      dialogModalData: [],
      dialogModalLoading: false,
      dialogParams: {
        pageNum: 1,
        pageSize: 10,
      },
      elevatorLoading: false,
      selections: [],
      elevatorTableData: [],
      elevatorDialogModalData: [],
      elevatorDialogSelections: [],
      elevatorQueryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      isAppend: false,
      relatedModelList: [],
      exportLoading: false,
    };
  },
  computed: {},
  watch: {},
  methods: {
    handleCommand(command, row) {
      switch (command) {
        case "deleteRow":
          this.deleteRow(row);
          break;
        case "toEdit":
          this.toEdit(row);
          break;
        default:
          break;
      }
    },
    parseTime,
    toViewElevator(row) {
      this.$refs.seeElevator.open();
      this.$set(this.dialogParams, 'id', row.id);
      this.getDialogList()
    },

    getDialogList(val) {
      this.dialogModalLoading = true;
      getRelationByIdValidation({
        ...this.dialogParams,
      }).then(res => {
        if (res && res.rows) {
          this.dialogModalData = res.rows
          this.dialogParams.total = parseInt(res.total);
        }

      }).finally(() => {
        this.dialogModalLoading = false;

      })

    },
    formatDict(value,dictType){
      let labelStr = '';
      for(let i =0;i< this.dict.type[dictType].length;i++){
        let item = this.dict.type[dictType][i]
        if(item.value == value){
          labelStr = item.label;
          break;
        }
      }
      return  labelStr;
    },
    /** 导出按钮操作 */
    handleExport() {
          this.exportLoading = true;
          downloadTemplate({ tableType: 8, withData: true, downloadFileName: `校验规则_${moment().format('YYYYMMDD')}.xlsx` })
            .finally(() => this.exportLoading = false)
    },
    getList() {
      this.loading = true;
      const params = JSON.parse(JSON.stringify(this.queryParams));
      delete params.updateTime
      listValidation(params).then(res => {
        this.tableData = res.rows;
        this.total = res.total;
        this.queryParams.total = res.total;
      }).finally(() => {
        this.loading = false;
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      }
      this.handleQuery();
    },
    toAdd() {
      this.$tab.openPage(this.$t('validation.addRule'), '/param/validationConfig/secondaryPage/0', { type: 1 })
    },
    toView(row) {
      this.$tab.openPage(this.$t('validation.detailRule'), '/param/validationConfig/secondaryPage/' + row.id, {
        type: 4,
        id: row.id
      })
    },
    toEdit(row) {
      this.$tab.openPage(this.$t('validation.editRule'), '/param/validationConfig/secondaryPage/' + row.id, {
        type: 2,
        id: row.id
      })
    },
    deleteRow(row) {
      this.$modal.confirm(this.$t('common.isDelete')).then(() => {
        deleteValidation({ id: row.id, updateTime: row.updateTime }).then(res => {
          if (res) {
            this.$message.success(this.$t('common.deleteSuccess'));
            this.handleQuery();
          }
        })
      })
    },
    handleRowStatus(val, row) {
      let msg = row.status === '1' ? this.$t('validation.enbaleConfrim') : this.$t('validation.disabledConfirm');
      this.$confirm(msg, this.$t('common.tips'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        confirmButtonClass: "el-icon-circle-check",
        cancelButtonClass: "el-icon-remove-outline",
        type: 'warning'
      }).then(() => {
        changeValidationStatus({ id: row.id, status: row.status, updateTime: row.updateTime }).then(res => {
          if (res) {
            let operationMsg = row.status === '1' ? this.$t('common.deactivatSuccess') : this.$t('common.enableSuccess');
            this.$message.success(operationMsg);
            this.getList();
          }
        })
      }).catch(() => {
        this.$set(row, 'status', val === '1' ? '0' : '1');
      })
    },
    handleSelectionChange(items) {
      this.selections = items
    },
    async handleRelateElevator(isAppend) {
      if (this.selections.length === 0) {
        this.$message.error(this.$t('请选择一条联动数据'))
        return
      }
      this.isAppend = isAppend
      await this.getElevatorList();
      this.$refs.suitModelDialog.open(true);

    },
    handleConfirm() {
      if (this.elevatorDialogSelections.length === 0) {
        this.$message.error(this.$t('请选择一条关联梯型数据'))
        return
      }

      batchChangeRelation({
        elevatorModelIds: this.elevatorDialogSelections.map(item => item.elevatorModelId),
        relatedCaseIds: this.selections.map(item => item.id),
        isAppend: this.isAppend,
      }).then(res => {
        if (res.code == 200) {
          this.$message.success(this.$t('操作成功'))
          this.getList();
        }
      })
    },
    getElevatorList() {
      this.elevatorLoading = true;
      listForComponents(this.elevatorQueryParams).then(res => {
        this.elevatorDialogModalData = res.rows;
        this.elevatorQueryParams.total = res.total;
        this.elevatorLoading = false;
      })
    },
    elevatorSelectionChange(val) {
      this.elevatorDialogSelections = val;
    },
    handleElevatorQuery() {
      this.elevatorQueryParams.pageNum = 1
      this.getElevatorList();
    },
    resetElevatorQuery() {
      this.$set(this.elevatorQueryParams, 'pageNum', 1);
      this.$set(this.elevatorQueryParams, 'pageSize', 10);
      this.$set(this.elevatorQueryParams, 'areaName', null);
      this.$set(this.elevatorQueryParams, 'areaNameES', null);
      this.$set(this.elevatorQueryParams, 'areaNameRU', null);
      this.$set(this.elevatorQueryParams, 'areaNameUS', null);
      this.$set(this.elevatorQueryParams, 'elevatorModel', null);
      this.getElevatorList();
    },

    /**  获取关联梯型list */
    getRelatedModelList() {
      let params = {
        language: this.$i18n.locale,
        showType: false,
        relatedType: "3"
      }
      getRelatedModelList(params).then(response => {
        this.relatedModelList = [];
        response.forEach(item => {
          this.relatedModelList.push(
            {
              value: item.parabarId,
              label: item.relatedModel,
              areaId: item.areaId,
              elevatorType: item.elevatorType,
              elevatorModel: item.elevatorModel
            }
          )
        });
      });
    },
  },


  created() {
    this.getRelatedModelList()
  },
  mounted() {
    this.handleQuery();
  },
  activated() {
    this.getRelatedModelList()
    this.getList();
  }


}


</script>

<style scoped>

</style>

