<template>
  <div class="app-container">

    <card-table :del-prop="['createTime']" :loading="loading" :modalData="targetList" :searchParams="queryParams"
                :tableSearch="true" labelWidth="120px" @columnSearch="handleQuery" @pagination="getList"
                @resetList="resetQuery" @selection-change="handleSelectionChange">


      <template #operations="{selections}">
        <!--<el-button v-hasPermi="['user:target:add']" icon="el-icon-plus" plain size="mini" type="primary"-->
        <!--           @click="handleAdd"-->
        <!--&gt;{{ $t('common.add') }}-->
        <!--</el-button>-->
        <el-button v-hasPermi="['user:target:export']" icon="el-icon-download" size="mini" plain
                   @click="handleExport">{{ $t('common.export') }}
        </el-button>
      </template>

      <template #default="{ list }">
        <el-table-column align="center" type="selection" width="55"/>
        <el-table-column align="center" label="No" type="index" width="50"/>
        <!-- 代理商编号 -->
        <Column :label="$t('agent.agentNo')" align="center" prop="agentNo" showSearch/>
        <!--代理商名称-->
        <Column :label="$t('agent.agentName')" align="center" prop="agentName" showSearch/>
        <!--所属区域-->
        <Column :label="$t('agent.area')" :labelProp="'areaName' + localLabelSuffix" :searchDict="areaOptions"
                :showSearch="true" prop="areaIds" searchType="select" selectMore valueProp="areaId">
          <template #default="{ row }">
            <span>{{ getAgentName(row.areaId) }}</span>
          </template>
        </Column>
        <!--类型-->
        <Column :label="$t('agent.type')" :searchDict="dict.type.agent_type"
                :showSearch="true" prop="agentTypes"
                searchType="select" select-more>
          <template #default="{ row }">
            <span>{{ row.agentTypeName }}</span>
          </template>
        </Column>
        <!--代理商等级-->
        <Column :label="$t('agent.agentLevel')" :searchDict="dict.type.agent_level"
                :showSearch="true" prop="agentLevels"
                searchType="select" selectMore>
          <template #default="{ row }">
            <span>{{ row.agentLevelName }}</span>
          </template>
        </Column>
        <!--考核年度-->
        <Column :label="$t('target.targetYear')" align="center" prop="targetYear" show-search search-type="dateRange"
                :searchParams="queryParams" date-type="year">
          <template #default="{ row }">
            <!--<span>{{ row.targetYear }}</span>-->
            <span>{{ row.targetYear ? $moment(row.targetYear).format('YYYY') : '-' }}</span>
          </template>
        </Column>
        <!--目标台数-->
        <Column :label="$t('target.targetCount')" align="center" prop="targetElevatorCount" :sortable="true"/>
        <!--实际发货台数-->
        <Column :label="$t('target.actualCount')" align="center" prop="actualElevatorCount" :sortable="true"/>
        <!--完成率-->
        <Column :label="$t('target.completionRate')" align="center" prop="completeRate" :sortable="true">
          <template #default="{ row }">
            <span>{{ completeRate(row.targetElevatorCount, row.actualElevatorCount) }}</span>
          </template>
        </Column>

        <!--币种汇率-->
        <Column :label="$t('project.currency')" search-type="select" :search-dict="dict.type.currency_type"
                show-search select-more select-prop="currencies" prop="currency" width="200"/>

        <!--目标金额-->
        <Column :label="$t('target.targetMoney')" align="right" prop="targetMoney" :sortable="true">
          <template #default="{ row }">
            <!--每三位一个逗号-->
            <span>{{ row.targetMoney ? toDecimal2(numFormat(row.targetMoney)) : '-' }}</span>
          </template>
        </Column>
        <!--实际发货金额-->
        <Column :label="$t('target.actualMoney')" align="right" prop="actualMoney" :sortable="true">
          <template #default="{ row }">
            <!--每三位一个逗号-->
            <span>{{ row.actualMoney ? toDecimal2(numFormat(row.actualMoney)) : '-' }}</span>
          </template>
        </Column>
        <!--&lt;!&ndash;完成率&ndash;&gt;-->
        <!--<Column :label="$t('target.completionRate')" align="center" prop="completeRate">-->
        <!--  <template #default="{ row }">-->
        <!--    <span>{{ completeRate(row.targetMoney, row.actualMoney) }}</span>-->
        <!--  </template>-->
        <!--</Column>-->
        <!--标杆项目数-->
        <Column :label="$t('target.targetProjectCount')" align="center" prop="targetProjectCount" :sortable="true"/>
        <!--实际标杆项目数-->
        <Column :label="$t('target.actualProjectCount')" align="center" prop="actualProjectCount" :sortable="true"/>
        <!--&lt;!&ndash;完成率&ndash;&gt;-->
        <!--<Column :label="$t('target.completionRate')" align="center" prop="completeRate">-->
        <!--  <template #default="{ row }">-->
        <!--    <span>{{ completeRate(row.targetProjectCount, row.actualProjectCount) }}</span>-->
        <!--  </template>-->
        <!--</Column>-->
        <!--操作-->
        <Column :label="$t('common.operate')" :min-width="200" :showSearch="true" align="center" fixed="right"
                search-type="operate"
                width="250px">
          <!--<template #default="{ row }">-->
          <!--查看-->
          <!--<el-button v-hasPermi="['user:target:detail']" icon="el-icon-view" size="mini" type="text"-->
          <!--           @click="handleView(row)">{{ $t('common.view') }}-->
          <!--</el-button>-->
          <!--<el-dropdown v-hasPermi="['user:target:edit', 'user:target:remove']" 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">-->
          <!--    &lt;!&ndash;修改&ndash;&gt;-->
          <!--    <el-dropdown-item v-hasPermi="['user:target:edit']" command="handleUpdate"-->
          <!--                      icon="el-icon-edit">{{ $t('common.edit') }}-->
          <!--    </el-dropdown-item>-->
          <!--    &lt;!&ndash;删除&ndash;&gt;-->
          <!--    <el-dropdown-item v-hasPermi="['user:target:remove']" command="handleDelete"-->
          <!--                      icon="el-icon-delete">{{ $t('common.delete') }}-->
          <!--    </el-dropdown-item>-->
          <!--  </el-dropdown-menu>-->
          <!--</el-dropdown>-->

          <!--</template>-->
        </Column>

      </template>
    </card-table>


  </div>
</template>

<script>
import {addTarget, delTarget, getTarget, listTarget, updateTarget} from "@/api/user/target";
import CardTable from "@/components/element/table/CardTable.vue";
import Column from "@/components/element/table/Column.vue";
import {getAreaByUser} from "@/api/common/common";
import {parseTime} from "../../../utils/ruoyi";

export default {
  name: "Target",
  components: {Column, CardTable},
  dicts: ['agent_type', 'agent_level', 'currency_type'],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 代理商考核表格数据
      targetList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        total: 0,
        pageNum: 1,
        pageSize: 10,

        agentNo: null,
        agentName: null,
        areaIds: null,
        agentTypes: null,
        agentLevels: null,

        agentId: null,
        targetYear: null,
        targetMoney: null,
        actualMoney: null,
        targetElevatorCount: null,
        actualElevatorCount: null,
        targetProjectCount: null,
        actualProjectCount: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},

      // 区域选项
      areaOptions: [],
      // 快速查询
      areaMap: new Map(),
    };
  },

  computed: {
    localLabelSuffix() {
      // 从localstorage中获取语言
      return localStorage.getItem('labelSuffix');
    }
  },

  created() {
    this.getList();

    this.getArea();
  },
  methods: {
    /** 查询代理商考核列表 */
    async getList() {
      this.loading = true;
      try {
        // console.log('queryParams', this.queryParams)
        console.log(this.queryParams.targetYear)
        if (this.queryParams.targetYear) {
          this.queryParams.targetYear = this.$moment(this.queryParams.targetYear).format('YYYY-MM-DD HH:mm:ss')
        }
        // TODO 排除无用参数 ：currency
        const response = await listTarget(this.queryParams);
        this.targetList = response.rows;
        this.targetList.forEach(item => {
          item.agentLevelName = this.dict.label.agent_level[item.agentLevel];
          item.agentTypeName = this.dict.label.agent_type[item.agentType];
        });
        // this.total = response.total;
        this.queryParams.total = response.total;
      } finally {
        this.loading = false;
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        targetId: null,
        agentId: null,
        targetYear: null,
        targetMoney: null,
        actualMoney: null,
        targetElevatorCount: null,
        actualElevatorCount: null,
        targetProjectCount: null,
        actualProjectCount: null,
        delFlag: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.agentNo = null;
      this.queryParams.agentName = null;
      this.queryParams.areaIds = null;
      this.queryParams.agentTypes = null;
      this.queryParams.agentLevels = null;
      this.queryParams.targetYear = null;
      this.queryParams.targetMoney = null;
      this.queryParams.actualMoney = null;
      this.queryParams.targetElevatorCount = null;
      this.queryParams.actualElevatorCount = null;
      this.queryParams.targetProjectCount = null;
      this.queryParams.actualProjectCount = null;
      this.queryParams.currency = null;
      this.queryParams.currencies = null;


      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.targetId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加代理商考核";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const targetId = row.targetId || this.ids
      getTarget(targetId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改代理商考核";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.targetId != null) {
            updateTarget(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTarget(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const targetIds = row.targetId || this.ids;
      this.$modal.confirm('是否确认删除代理商考核编号为"' + targetIds + '"的数据项？').then(function () {
        return delTarget(targetIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const fileName = this.$t('agent.exportFielName') + parseTime(new Date(), '{y}{m}{d}') + '.xlsx'
      this.download('user/target/export', {
        ...this.queryParams,
        targetIds: this.ids || null,
      }, fileName)
    },

    // 下拉
    async getArea() {
      try {
        const response = await getAreaByUser();
        this.areaOptions = response.data;
        this.areaMap = response.data.reduce((map, obj) => {
          map.set(obj.areaId, obj);
          return map;
        }, new Map());
      } catch (e) {
      }
    },

    getAgentName(areaId) {
      if (areaId !== null && areaId !== undefined && areaId >= 0) {
        const area = this.areaMap.get(areaId);
        if (area) {
          return area['areaName' + this.localLabelSuffix]
        }
      }
      return '-'
    },

    completeRate(target, actual) {
      return (!!actual || actual === 0) && (!!target) ? (actual / target * 100).toFixed(2) + '%' : '-'
    },
  }
};
</script>
