<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="项目名称" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入项目名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-document-add"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="typeList"
      @selection-change="handleSelectionChange"
      ref="multipleTable"
    >
      <el-table-column label="项目名称" align="center" prop="projectName" />
      <el-table-column label="广告主名称" align="center" prop="advertiserName" />
      <el-table-column label="媒体" align="center" prop="mediaCode">
        <template slot-scope="scope">
          <div v-if="scope.row.mediaCode">
            {{ scope.row.mediaCode | mediaName }}
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
      <el-table-column label="销售" align="center" prop="saleName" />
      <el-table-column label="运营" align="center" prop="operatorName" />
      <el-table-column label="设计" align="center" prop="designResponsibleName" />
      <el-table-column label="转化目标" align="center" prop="ocpxActionType">
        <template slot-scope="scope">
          <div v-if="scope.row.ocpxActionType">
            <span
              v-for="(item, index) in JSON.parse(scope.row.ocpxActionType)"
              :key="index"
            >
              {{ item.ocpxName + "(" + (item.maxValue / 1000).toFixed(2) + ")" }}
              <br />
            </span>
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >编辑</el-button
          >
          <el-button size="mini" type="text" @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="媒体类型" prop="mediaCode">
          <el-radio-group v-model="form.mediaCode">
            <el-radio-button label="JN">磁力金牛</el-radio-button>
            <el-radio-button label="QC" disabled>千川</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName">
          <el-input
            v-model="form.projectName"
            placeholder="请输入项目名称"
            clearable
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="供应商" prop="supplierCode">
          <el-input
            v-model="form.supplierCode"
            placeholder="请输入供应商"
            clearable
            style="width: 240px"
          />
        </el-form-item>

        <el-form-item label="广告主" prop="advertiserId">
          <el-select
            ref="optionAdvertiser"
            v-model="form.advertiserId"
            placeholder="选择广告主"
            clearable
            style="width: 240px"
            filterable
          >
            <el-option
              v-for="item in formList.advertiserList"
              :key="item.id"
              :label="item.advertiserName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="销售" prop="saleId">
          <el-select
            ref="optionSale"
            v-model="form.saleId"
            placeholder="选择销售"
            clearable
            style="width: 240px"
            filterable
          >
            <el-option
              v-for="item in formList.personList"
              :key="item.userId"
              :label="item.nickName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="运营" prop="operatorId">
          <el-select
            ref="optionOperator"
            v-model="form.operatorId"
            placeholder="选择运营"
            clearable
            style="width: 240px"
            filterable
          >
            <el-option
              v-for="item in formList.personList"
              :key="item.userId"
              :label="item.nickName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设计" prop="designResponsibleId">
          <el-select
            ref="optionDesignResponsible"
            v-model="form.designResponsibleId"
            placeholder="选择设计"
            clearable
            style="width: 240px"
            filterable
          >
            <el-option
              v-for="item in formList.personList"
              :key="item.userId"
              :label="item.nickName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="优化目标" prop="ocpxActionType">
          <el-select
            v-model="form.ocpxActionType"
            placeholder="选择优化目标"
            clearable
            style="width: 240px"
            multiple
            @change="selectOcpx"
            filterable
            ref="optionOcpx"
          >
            <el-option
              v-for="item in formList.ocpxActionList"
              :key="item.code"
              :label="item.name"
              :value="item.code + '@' + item.name"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="进入直播间最高出价" prop="mobile">
          <el-input-number
            style="width: 240px"
            v-model="form.commissionRate"
            :precision="2"
            :step="0.1"
            :min="0"
            placeholder="请输入进入直播间最高出价"
          ></el-input-number>
        </el-form-item> -->
        <el-form-item
          v-for="(domain, index) in form.ocpxActionTypeList"
          :label="domain.ocpxName + '最高出价'"
          :key="domain.ocpxCode"
          :prop="'ocpxActionTypeList.' + index + '.maxValue'"
          :rules="{
            required: true,
            message: '出价不能为空',
            trigger: 'blur',
          }"
        >
          <el-input-number
            :precision="2"
            :step="0.1"
            :min="0"
            v-model="domain.maxValue"
            style="width: 240px"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="confirmLoading"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getProjectList,
  addProject,
  editProject,
  peojectDeleteById,
  getOcpxActionType,
  getAdvertiserList,
} from "@/api/accountManagement/accountManagement";
import { listUser } from "@/api/system/user";
export default {
  name: "ProjectList",
  data() {
    return {
      dialogTableVisible: false,
      logPage: {
        pageNum: 1,
        pageSize: 10,
      },
      logData: [],
      logTotal: 0,
      logLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 编辑所用id
      updateId: null,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      typeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 分配销售
      openAllocation: false,
      // 选择的销售id
      saleId: undefined,
      // 获取用户id
      userId: undefined,
      // 销售列表
      saleList: [],
      // 分配销售确定loading
      confirmLoadingSale: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectName: undefined,
        advertiserId: undefined,
      },
      //查询参数所用下拉数据
      queryParamsList: {},
      // 表单参数
      form: {
        ocpxActionTypeList: [],
      },
      //上传报表下拉数据
      formList: {
        personList: [], //新增下拉人员列表
        ocpxActionList: [], //优化目标列表
        advertiserList: [], //广告主列表
      },
      fileList: [],
      //获取销售线索文件流
      dateFile: null,
      //销售线索上传loading
      confirmLoading: false,
      // 表单校验
      rules: {
        projectName: [{ required: true, message: "项目名称必填", trigger: "blur" }],
        saleId: [{ required: true, message: "请选择销售", trigger: "change" }],
        advertiserId: [{ required: true, message: "请选择广告主", trigger: "change" }],
        ocpxActionType: [
          { required: true, message: "请选择转化目标", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.userId = this.$store.getters.userId;
  },
  filters: {
    ocpxActionTypeName(status) {
      const statusMap = {
        72: "涨粉",
        395: "订单支付",
        192: "直播推广 ROI",
      };
      return statusMap[status];
    },
    mediaName(status) {
      const statusMap = {
        JN: "磁力金牛",
      };
      return statusMap[status];
    },
  },
  mounted() {
    this.$nextTick(() => {
      if (this.$route && this.$route.query.id) {
        this.queryParams.advertiserId = this.$route.query.id;
      }
      this.getList();
      this.listUser();
      this.getOcpxActionType();
      this.getAdvertiserList();
    });
  },
  methods: {
    listUser() {
      listUser({ pageNum: 1, pageSize: 10000 }).then((res) => {
        this.formList.personList = res.rows;
      });
    },
    getAdvertiserList() {
      getAdvertiserList({ pageNum: 1, pageSize: 10000 }).then((res) => {
        this.formList.advertiserList = res.rows;
      });
    },

    getOcpxActionType() {
      getOcpxActionType().then((res) => {
        this.formList.ocpxActionList = res.result;
      });
    },
    /** 复选框禁用 */
    selectable(row, index) {
      return true;
      // if (!!row.saleName) {
      //   return false;
      // } else {
      //   return true;
      // }
    },

    /** 查询字典类型列表 */
    getList() {
      this.loading = true;
      getProjectList({ ...this.queryParams, userId: this.userId }).then((response) => {
        this.typeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.confirmLoading = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.dateFile = null;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.pageNum = 1;
      // this.handleQuery();
      this.getList();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新建项目";
      this.$nextTick(() => {
        this.$set(this.form, "mediaCode", "JN");
        this.$refs["form"].clearValidate("ocpxActionType");
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
    },

    selectOcpx(item) {
      console.log(item);

      this.$set(
        this.form,
        "ocpxActionTypeList",
        item.map((value) => {
          return {
            ocpxCode: value.split("@")[0],
            ocpxName: value.split("@")[1],
            maxValue: undefined,
          };
        })
      );
      console.log(this.form.ocpxActionTypeList);
    },
    handleUpdate(item) {
      this.reset();
      this.open = true;
      this.title = "修改项目";
      this.$nextTick(() => {
        this.updateId = item.id;
        this.$set(this.form, "projectName", item.projectName);
        this.$set(this.form, "mediaCode", item.mediaCode);
        this.$set(this.form, "supplierCode", item.supplierCode);
        this.$set(this.form, "saleId", item.saleId);
        this.$set(this.form, "operatorId", item.operatorId);
        this.$set(this.form, "designResponsibleId", item.designResponsibleId);
        this.$set(
          this.form,
          "ocpxActionType",
          JSON.parse(item.ocpxActionType).map((value) => {
            return value.ocpxCode + "@" + value.ocpxName;
          })
        );
        this.$set(
          this.form,
          "ocpxActionTypeList",
          JSON.parse(item.ocpxActionType).map((value) => {
            return {
              ocpxCode: value.ocpxCode,
              ocpxName: value.ocpxName,
              maxValue: value.maxValue / 1000,
            };
          })
        );
        this.$set(this.form, "advertiserId", +item.advertiserId);
      });
    },
    /** 删除按钮 */
    handleDelete(item) {
      this.$modal
        .confirm(`请确认是否删除此项目？删除会同时删除项目下账户`)
        .then(() => {
          var params = {};
          params.id = item.id;
          params.userId = this.$store.getters.userId;
          peojectDeleteById(params)
            .then((res) => {
              this.$modal.msgSuccess("删除成功");
              this.resetQuery();
            })
            .catch(() => {
              this.$message.error("失败");
              this.loading = false;
            });
        })
        .catch(() => {});
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          var params = { ...this.form };
          params.createBy = this.userId;
          params.ocpxActionType = JSON.stringify(
            this.form.ocpxActionTypeList.map((item) => {
              return {
                ...item,
                maxValue: item.maxValue * 1000,
              };
            })
          );
          params.saleName = this.$refs.optionSale.selected.label;
          params.operatorName = this.$refs.optionOperator.selected.label;
          params.designResponsibleName = this.$refs.optionDesignResponsible.selected.label;

          params.advertiserName = this.$refs.optionAdvertiser.selected.label;
          //   params.advertiserId = 2;
          if (!!this.updateId) {
            editProject({ ...params, id: this.updateId }).then((res) => {
              this.open = false;
              this.confirmLoading = false;
              this.resetQuery();
            });
          } else {
            addProject(params).then((res) => {
              this.open = false;
              this.confirmLoading = false;
              this.resetQuery();
            });
          }
        }
      });
    },
  },
};
</script>
