<template>
  <div class="app-container">
    <el-dialog :visible.sync="addVisibledx" :title="xiugai ? '修改' : '添加定向计划'" width="1100px">
      <el-form ref="dxForm" :rules="addRulesdx" :model="dxForm" status-icon label-position="left" label-width="100px"
        style="width:950px; margin-left:20px;">
        <el-row>
          <el-col :span="12">
            <el-form-item label="计划名称" prop="planName">
              <el-input :disabled="xiugai" v-model="dxForm.planName" clearable style="width:100%;"
                oninput="if(value.length>20) value=value.slice(0,20)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划人电话" prop="merchantPhone" required>
              <el-input type="number" v-model="dxForm.merchantPhone" max-length="11"
                oninput="if(value.length>20) value=value.slice(0,11)" clearable style="width:100%;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="计划类型" prop="planType">
              <el-select :disabled="xiugai" v-model="dxForm.planType" clearable class="filter-item" style="width:100%;"
                placeholder="请选择计划类型">
                <template v-for="(item, index) in  planTypeMap">
                  <el-option :key="index" :label="item" :value="index" v-if="index != 1" />
                </template>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="达人服务商" prop="douyinIdList">
              <!-- <div style="height: 80px;overflow-y: auto" >
              <el-cascader style="width:100%;height: 66px;" v-model="dxForm.douyinIdList" placeholder="请选择达人信息" :options="providers"
                :props="{
                  expandTrigger: 'hover',
                  value: 'id',
                  label: 'name',
                  multiple: true,
                }" expand-trigger="hover" clearable /> -->
              <el-input :readonly="true" @click.native="handleSelectTalent" v-model="selectedTalent"
                style="width:100%;" />
              <!-- </div>
                <div>选中{{ dxForm.douyinIdList?dxForm.douyinIdList.length:0 }}个达人</div>  -->
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="计划时间" prop="chooseJhTime">
              <el-date-picker v-model="dxForm.chooseJhTime" :disabled="xiugai || dxForm.planType != 3"
                :picker-options="{}" style="width:100%;" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss"
                type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="佣金有效期" prop="commissionDuration">
              <el-input type="number" :disabled="xiugai || dxForm.planType != 3" v-model="dxForm.commissionDuration"
                style="width:100%;" clearable maxlength="4">
                <template slot="append">天</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row>
          <el-col :span="12">
           <el-form-item label="达人抖音号" prop="douyinIdList">
              <el-select v-model="dxForm.douyinIdList" multiple filterable clearable class="filter-item"
                style="width:100%;" placeholder="请选择达人抖音号">
                <el-option v-for="(item, index) in  darenList" :key="index"
                  :label="item.nickName + '(' + item.talentId + ')'" :value="item.talentId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>-->
        <!-- <el-form-item label="选择抖音商品">
          <el-select v-model="chooseTempgoods" style="width:100%" @change="selectdygoods" filterable clearable class="filter-item"
            placeholder="请选择带货商品">
            <el-option v-for="(item, index) in  dyGoodsList" :key="index"
              :label="item.goodsName + '(' + item.goodsName + ')'" :value="item.dyGoodsNo" />
          </el-select>
        </el-form-item> -->

        <div style="color: green;float: right;">note:佣金比例在0%-29%,使用万分位,如500表示5%</div>
        <el-table :data="dyGoodsList" border highlight-current-row height="400px">
          <el-table-column label="抖音商品id" prop="dyGoodsNo" width="180px" />
          <el-table-column label="抖音商品名称" prop="goodsName" />
          <el-table-column label="商品的定向抽佣率，万分数" prop="commissionRate">
            <template slot-scope="scope">
              <el-input type="number" v-model="scope.row.commissionRate" style="width:200px" clearable />
            </template>
          </el-table-column>
          <el-table-column label="操作" prop="" width="100px">
            <template slot-scope="scope">
              <el-button type="text" icon="el-icon-edit" size="mini" @click="deltempListRow(scope.$index)">删除
              </el-button>
            </template>
          </el-table-column>

        </el-table>



      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addVisibledx = false; dxForm = {};
        chooseTempgoods = []; $refs.dxForm.resetFields(); tempList = [];">取消</el-button>
        <el-button type="primary" @click="handleAdddx()">确定</el-button>
      </div>

    </el-dialog>

    <!-- 选择达人 -->
    <selectTalentRef ref="selectTalentRef" />

  </div>
</template>

<script>
import selectTalentRef from "./selectTalentRef.vue";
import { createNonCommonPlan, dyGoodsGoodsList, talentList, updatePlanStatus, selectProvider, talentByPlan } from "@/api/dyApp";
import moment from "moment";

export default {
  name: "Coupon",
  components: { selectTalentRef },
  data() {
    var validateProvider = (rule, value, callback) => {
      if (this.dxForm.provider.length == 0 && this.dxForm.douyinIdList.length == 0)
        callback(new Error("请选择达人或服务商"));
      else callback();
    };

    var validateType = (rule, value, callback) => {
      if (this.dxForm.planType == 3 && (this.dxForm.chooseJhTime.length == 0))
        callback(new Error("请选择计划时间"));
      else callback();
    };

    var validateDuration = (rule, value, callback) => {
      if (this.dxForm.planType == 3 && this.dxForm.commissionDuration == '')
        callback(new Error("请选择佣金有效期"));
      else callback();
    };

    return {
      xiugai: false,
      total: 0,
      list: [],
      dyGoodsList: [],
      planTypeMap: {
        1: '通用计划',
        2: '直播间定向计划',
        3: '短视频定向计划'
      },
      contentTypeMap: {
        1: '仅短视频',
        2: '仅直播间',
        3: '短视频和直播间'
      },
      planStatusMap: {
        1: "进行中",
        2: "已完成",
        3: "已取消"
      },

      dxForm: {
        douyinIdList: [],
        merchantPhone: '',
        productList: [],
        planName: '',
        chooseJhTime: [],//临时变量
        planStartTime: '',
        planEndTime: '',
        commissionDuration: '',
        planType: '',
        provider: [],
      },
      chooseTempgoods: [],
      tempList: [],
      addVisibledx: false,
      addRulesdx: {
        planName: [{ required: true, message: '计划名称不能为空', trigger: 'blur' }],
        planType: [{ required: true, message: '请选择计划类型', trigger: 'blur' }],
        douyinIdList: [{ required: true, message: '请选择达人号', trigger: 'blur' }],
        provider: [{ validator: validateProvider, required: true, message: '请选择达人服务商', trigger: 'blur' }],
        chooseJhTime: [{ validator: validateType, required: true, message: '请选择计划时间', trigger: 'change' }],
        commissionDuration: [{ validator: validateDuration, required: true, message: '佣金有效期不能为空', trigger: 'blur' }],
        merchantPhone: [{ required: true, message: '联系电话不能为空', trigger: 'blur' }, { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }],
      },
      darenList: [],
      providers: [],//服务商信息
      dySelectedTalent: [],
      selectedTalent: "选中0个达人",
    };
  },
  created() {
    this.getProviderList();//获取达人服务商
  },
  methods: {
    handleSelectTalent() {
      //console.info(this.dxForm)
      this.$refs.selectTalentRef.load(this.dxForm.plan_id);
    },
    confirmSelectTalent(talents) {
      this.dxForm.douyinIdList = talents;
      this.selectedTalent = "选中" + this.dxForm.douyinIdList.length + "个达人";
    },
    updateDingxiang(data) {
      //console.info(data)
      //修改通用计划getTalentList
      this.addVisibledx = true;
      this.xiugai = true;

      this.getdyGoods(data.planId);


      let dyidlist = [];
      // data.dyTalentList.forEach(e => {
      //   dyidlist.push(e.talentId)
      // })

      let gdlist = [];
      // data.goodsList.forEach(e => {
      //   gdlist.push({ product_id: e.roductId, commission_rate: e.commissionRate });
      // })

      this.tempList = gdlist;
      this.dxForm = {
        douyinIdList: dyidlist,
        merchantPhone: data.merchantPhone,
        productList: gdlist,
        planName: data.planName,
        planStartTime: this.dateForm(data.planStartTime),
        planEndTime: this.dateForm(data.planEndTime),
        commissionDuration: data.commissionDuration,
        planType: (data.planType).toString(),
        chooseJhTime: [this.dateForm(data.planStartTime), this.dateForm(data.planEndTime)],
        plan_id: data.planId
      };

      this.getTalentByPlan(data.planId);

    },
    configUpState() {
      if (this.tempRow.planStatus == null || this.tempRow.planStatus == '') {
        this.$notify.error({
          title: '提示',
          message: '请选择状态'
        })
        return
      }
      let req = [{ plan_id: this.tempRow.planId, status: this.tempRow.planStatus, planType: this.tempRow.planType }];
      updatePlanStatus(req).then(response => {
        this.showView = false;
        this.$notify.success({
          title: '成功',
          message: '操作成功'
        });
        if (this.xiugai) {
          this.$emit('getDetail');
        } else {
          this.$emit('getList');
        }

      }).catch(response => {
        this.$notify.error({
          title: '失败',
          message: response.data.errmsg
        })
      })

    },
    updateUpState(row) {
      this.showView = true;
      this.tempRow = {};
      this.tempRow = row;
    },
    handleAdddx() {

      this.$refs['dxForm'].validate((valid) => {
        if (valid) {
          if (this.dxForm.planType === "3") {
            this.dxForm.planStartTime = this.dxForm.chooseJhTime[0];
            this.dxForm.planEndTime = this.dxForm.chooseJhTime[1];
          }
          //判断是否选择了商品
          this.tempList = [];
          this.dyGoodsList.forEach(goods => {
            if (goods.commissionRate != null && goods.commissionRate != '' && goods.commissionRate >= 0)
              this.tempList.push({ productId: goods.dyGoodsNo, commissionRate: goods.commissionRate });
          });

          if (this.tempList.length === 0) {
            this.$notify.error({
              title: '失败',
              message: '请至少选择一个商品并填写佣金'
            })
            return;
          }
          console.info(this.tempList);
          this.dxForm.productList = this.tempList;
          //处理选中的达人
          let data = Object.assign({}, this.dxForm);
          //20230718屏蔽
          // let talentId = [];
          // data.douyinIdList.forEach(item => {
          //   talentId.push(item[1]);
          // })
          // data.douyinIdList = talentId;
          //防止未选达人时出错
          if (this.dxForm.douyinIdList == null)
            this.dxForm.douyinIdList = [];
          console.info(data);

          createNonCommonPlan(data).then(() => {
            this.addVisibledx = false;
            this.$refs.dxForm.resetFields();
            this.dxForm = {};
            this.$notify.success({
              title: '成功',
              message: '添加成功'
            });
            this.$emit('getList');
          }).catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
        }
      })
    },
    dateForm(el) {
      if (el)
        return moment(parseInt(el) * 1000).format('YYYY-MM-DD HH:mm:ss');
      return ""
    },
    selectdygoods(e) {
      if (e == null || e == '') {
        return;
      }
      let boo = false;
      this.tempList.forEach(t => {
        if (t.productId == e) {
          boo = true;
        }
      })

      if (boo) {
        return;
      }

      this.tempList.push({ productId: e, commissionRate: 0 });
    },
    deltempListRow(index) {
      console.log(index);
      this.dyGoodsList.splice(index, 1);
    },
    getgoodsName(goodsId) {
      let nm = "";
      this.dyGoodsList.forEach(e => {
        if (e.dyGoodsNo == goodsId) {
          nm = e.goodsName;
        }
      })
      return nm;
    },
    addDingxiang() {
      this.addVisibledx = true;
      this.xiugai = false;
      this.dxForm = {
        douyinIdList: [],
        merchantPhone: '',
        productList: [],
        planName: '',
        planStartTime: '',
        planEndTime: '',
        commissionDuration: '',
        planType: '',
        chooseJhTime: [],
        planId: ''
      };

      this.selectedTalent = "选中0个达人";
      this.getdyGoods(null);//获取抖音商品

    },
    getTalentByPlan(planId) {
      talentByPlan({ planId: planId }).then(res => {
        // res.data.data 类似 {"errno":0,"data":[["姚8月直播","Kora_888"]],"errmsg":"成功"},获取 每个二维数组的第二个元素组成一个新数组
        let talentId = [];
        res.data.data.forEach(item => {
          talentId.push(item[1]);
        })
        this.dxForm.douyinIdList =talentId;
        this.selectedTalent = "选中" + (this.dxForm.douyinIdList ? this.dxForm.douyinIdList.length : 0) + "个达人";
      })
    },
    getTalentList() {
      talentList({ pageNum: 1, pageSize: 999 })
        .then((response) => {
          this.darenList = response.data.data.list;
        })
    },
    async getProviderList() {
      console.info('getProviderList')
      await selectProvider().then(res => {
        this.providers = res.data.data;
      })
    },
    async getdyGoods(planId) {
      await dyGoodsGoodsList({ pageNum: 1, pageSize: 999, planId: planId })
        .then((res) => {
          this.dyGoodsList = res.data.data.list;
        })
    },
  },
  beforeCreate() {
    // vm = this;
  },

};
</script>
<style scoped>
.el-form-item {
  margin-bottom: 18px;
}

.el-form--label-left .el-form-item__label {
  text-align: right;
}
</style>
