<template>
  <div id="addPlanList">
    <el-card>
      <span>基本信息</span>
      <el-form :model="basicForm" :rules="basicRules" ref="basic" label-width="auto">
        <el-row :gutter="10">
          <el-col :span="1.5">
              <el-form-item label="计划编码">
                <el-input
                  v-model="basicForm.planCode"
                  size="mini"
                  disabled
                  style="width: 200px"
                />
              </el-form-item>
          </el-col>

          <el-col :span="1.5">
            <el-form-item label="计划名称" prop="planName" :rules="{ required: true, message: '请填写名称', trigger: 'blur' }">
              <el-input
                v-model.trim="basicForm.planName"
                size="mini"
                :readonly="sonDisable"
                clearable
                style="width: 200px"
              />
            </el-form-item>
         </el-col>

         <el-col :span="1.5">
            <el-form-item label="线路类型" prop="type" :rules="{ required: true, message: '请选择线路类型', trigger: 'blur' }">
              <el-select :disabled="sonDisable" v-model="basicForm.type" size="mini" style="width: 200px">
                <el-option v-for="dict in dict.type.mk_plan_route_type" :key="dict.value" :label="dict.label" :value="dict.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="1.5">
            <el-form-item label="执行人" prop="chargerName" :rules="{ required: true, message: '请选择执行人', trigger: 'blur' }">
                <el-select clearable size="mini" v-model="basicForm.chargerName" :disabled="sonDisable" @focus="choose('CONTACTS_PARAM', true, '执行人')" style="width: 200px">
                  <el-option v-for="item in personOptions" :key="item.id" :label="item.name" :value="item.code" />
                </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="1.5">
            <el-form-item label="确认状态" prop="state">
              <el-select disabled v-model="basicForm.state" size="mini" style="width: 200px">
                <el-option v-for="dict in dict.type.mk_plan_state" :key="dict.value" :label="dict.label" :value="dict.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row :gutter="10">

          <el-col :span="1.5">
            <el-form-item label="开始时间" prop="startDate" :rules="{ required: true, message: '请选择开始时间', trigger: 'blur' }">
              <el-date-picker
                v-model="basicForm.startDate"
                :disabled="sonDisable"
                clearable
                type="date"
                value-format="yyyy-MM-dd"
                size="mini"
                style="width: 200px"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="1.5">
            <el-form-item label="截止时间" prop="deadlineTime" :rules="{ required: true, message: '请选择截止时间', trigger: 'blur' }">
              <el-date-picker
                v-model="basicForm.deadlineTime"
                :disabled="sonDisable"
                clearable
                type="date"
                value-format="yyyy-MM-dd"
                size="mini"
                style="width: 200px"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>

         <el-col :span="1.5">
            <el-form-item label="销售区域" prop="marketingAreaName" :rules="{ required: true, message: '请选择销售区域', trigger: 'blur' }">
              <el-select clearable v-model="basicForm.marketingAreaName" size="mini" :disabled="sonDisable" @focus="choose('MK_SALESAREA_PARAM', true, '销售区域')" style="width: 200px">
                <el-option
                  v-for="item in deptOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="1.5">
            <el-form-item label="部门" prop="deptName">
              <el-select clearable v-model="basicForm.deptName" size="mini" :disabled="sonDisable" @focus="choose('DEPT_PARAM', true, '部门')" style="width: 200px">
                <el-option
                  v-for="item in deptOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>

        <span>明细信息</span>
        <div class="btn_grooup">
          <el-button type="primary" size="mini" @click="addLine" v-if="!sonDisable">增行</el-button>
          <el-button type="primary" size="mini"  @click="copy" v-if="sonPageStu == 'check'">复制</el-button>
          <el-button type="primary" size="mini" @click="delItems" v-if="sonPageStu == 'edit'">批量删除</el-button>
          <el-button type="primary" size="mini" @click="edit" v-if="sonPageStu == 'check'">编辑</el-button>
        </div>

        <el-table 
          :data="basicForm.mkBoPlanItemList" 
          fit
          max-height="600"
          style="font-size: 12px;"
          @selection-change="handleSelectionChange"
          :cell-class-name="cellClassName"
        >
          <el-table-column type="selection" align="center"/>
          <el-table-column label="序号" type="index" align="center"/>
          <el-table-column show-overflow-tooltip label="计划编号" prop="planCode" width="150"/>
          <el-table-column show-overflow-tooltip label="日期"  prop="date" width="230px">
            <template slot-scope="scope">
              <el-form-item class="hang" :prop="'mkBoPlanItemList.' + scope.$index + '.' + 'date'" :rules="{ required: true, message: '请填写日期', trigger: 'blur' }">
                <el-date-picker
                  v-model="scope.row.date"
                  readonly
                  clearable
                  type="date"
                  size="mini"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column show-overflow-tooltip label="客户名称" prop="customerName" min-width="230">
            <template slot-scope="scope">
              <el-form-item class="hang" :prop="'mkBoPlanItemList.' + scope.$index + '.' + 'customerName'" :rules="{ required: true, message: '请选择客户', trigger: 'blur' }">
                <el-select clearable size="mini" v-model="scope.row.customerName" :disabled="sonDisable" @focus="chooseSon(scope.$index, 'CUSTOMER_PARAM_ZT', true, '客户')" style="width: 200px">
                  <el-option v-for="item in customerOptions" :key="item.id" :label="item.name" :value="item.code" />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column show-overflow-tooltip label="联系人" prop="contactName" min-width="230">
            <template slot-scope="scope">
              <el-form-item class="hang" :prop="'mkBoPlanItemList.' + scope.$index + '.' + 'contactName'" :rules="{ required: true, message: '请选择联系人', trigger: 'blur' }">
                <el-select clearable size="mini" v-model="scope.row.contactName" :disabled="sonDisable" @focus="chooseSon(scope.$index, 'LINKMAN_PARAM', true, '联系人', {})" style="width: 200px">
                  <el-option v-for="item in linkOptions" :key="item.id" :label="item.name" :value="item.code" />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column show-overflow-tooltip label="详细地址" prop="address" min-width="200">
            <template slot-scope="scope">
              <el-form-item class="hang" :prop="'mkBoPlanItemList.' + scope.$index + '.' + 'address'">
                <el-input clearable :readonly="sonDisable" size="mini" v-model="scope.row.address"/>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column show-overflow-tooltip label="拜访目的" prop="purpose" min-width="200">
            <template slot-scope="scope">
              <el-form-item class="hang" :prop="'mkBoPlanItemList.' + scope.$index + '.' + 'purpose'" :rules="{ required: true, message: '请选择拜访目的', trigger: 'blur' }">
                <el-select clearable :disabled="sonDisable" v-model="scope.row.purpose" size="mini">
                  <el-option v-for=" dict in dict.type.mk_bo_behavior_goal" :key="dict.value" :label="dict.label" :value="dict.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column :readonly="sonDisable" show-overflow-tooltip label="商机" prop="boName" min-width="200">
            <template slot-scope="scope">
              <el-form-item class="hang" :prop="'mkBoPlanItemList.' + scope.$index + '.' + 'boName'">
                <el-input clearable :readonly="sonDisable" size="mini" v-model="scope.row.boName"/>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column :readonly="sonDisable" show-overflow-tooltip label="营销活动" prop="marketingCampaign" min-width="200">
            <template slot-scope="scope">
              <el-form-item class="hang" :prop="'mkBoPlanItemList.' + scope.$index + '.' + 'marketingCampaign'">
                <el-input clearable :readonly="sonDisable" size="mini" v-model="scope.row.marketingCampaign"/>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column
            fixed="right"
            label="操作"
            align="center"
          >
            <template slot-scope="scope">
              <el-button type="text" size="mini" :disabled="sonDisable" @click="delLine(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </el-card>

    <div class="btn_group">
      <el-col :span="1.5">
        <el-button type="primary" size="mini" plain @click="save" v-if="sonPageStu == 'add' || sonPageStu == 'edit'">保存</el-button>
      </el-col>
      <!-- <el-col :span="1.5" style="margin: 0 10px;">
        <el-button type="primary" size="mini" plain @click="submit" v-if="sonPageStu == 'check' && (row.status == '0' || row.status == '3')">提交</el-button>
      </el-col> -->
      <el-col :span="1.5" style="margin: 0 10px;">
        <el-button size="mini" plain @click="back">返回</el-button>
      </el-col>

      <Refers ref="refer" @doSubmit="selectionsToInput" :single="true"/>

    </div>
  </div>
</template>

<script>
import {addPlan, getPlanDetail, editPlan, delPlanItem} from '@/api/business/spd/task_management/visitingPlan/visitingPlan.js'
import Refers from '@/components/Refers/refers.vue'
// 用于回显参照框数据
import {getRefer} from '@/api/purchase/basic.js'
export default {
  name: 'addPlanList',
  props: ['pageStu', 'row', 'disable'],
  dicts: ['mk_plan_state', 'mk_plan_route_type', 'mk_bo_behavior_goal'],
  components: {
    Refers
  },
  model: {
    prop: 'isList',
    event: 'jugislist'
  },
  data() {
    return {
      // 不能直接改变props传来的值
      sonPageStu: this.pageStu,
      sonDisable: this.disable,
      // dialog: {
      //   config: false
      // },
      basicForm: {
        id: '',
        planCode: '',
        planName :'',
        charger: '',
        chargerName: this.$store.state.user.nickName,
        dept: '',
        deptName: this.$store.state.user.deptName,
        startDate: this.getNextWeek(1),
        deadlineTime: this.getNextWeek(7),
        type: '0',
        state: '0',
        marketingArea: '',
        marketingAreaName: '',
        mkBoPlanItemList: []
      },
      delPlanItemList: [],
      basicRules: {},
      tableList: [],
      referCondition: {
        type: '',
        isPage: true,
        title: '',
      },
      // referCondition: {
      //   type: '',
      //   isPage: true,
      //   title: '',
      // },
      tableIndex: null,
      ids: [],
      linkOptions: [],
      manOptions: [],
      personOptions: [],
      deptOptions: [],
      customerOptions: [],
      salesAreaOptions: [],
      //判断默认明细行带出完毕后日期等于当前日期的标识
      isFlag: false
    }
  },
  updated() {},
  mounted() {},
  created() {
    //查看系统数据
    // console.log(this.$store.state.user, 'this.$store.state.user')
    if(this.pageStu == 'check') {
      console.log('数据', this.row)
      this.getDetails(this.row)
    } else if (this.pageStu == 'edit') {
      this.getDetails(this.row)
    } else if (this.pageStu == 'add') {
    //新增时默认带出7条明细行
    this.defaultDetailLine(7)
    }
  },
  methods:{
    copy() {
      this.isFlag = true;
      this.$modal.notifySuccess("复制成功");
      this.sonPageStu = 'add'
      this.sonDisable = false
      // this.getDetails(this.row)
      this.basicForm.id = ''
      this.basicForm.code = ''
      this.basicForm.createBy = ''
      this.basicForm.chargerName = this.$store.state.user.name
      this.basicForm.deptName = this.$store.state.user.deptId
      if (this.basicForm.chargerName) { this.reBackRefer('CONTACTS_PARAM', this.basicForm.chargerName) }
      if (this.basicForm.marketingAreaName) { this.reBackRefer('MK_SALESAREA_PARAM', this.basicForm.marketingAreaName) }
      if (this.basicForm.deptName) { this.reBackRefer('DEPT_PARAM', this.basicForm.deptName) }
      // this.basicForm.mkBoPlanItemList.forEach(item => {
        // item.date = ''
        // item.customer = ''
        // item.customerName = ''
        // item.contact = ''
        // item.contactName = ''
        // item.address = ''
        // item.purpose = ''
        // item.bo = ''
        // item.boName = ''
        // item.marketingCampaign = ''
      // })
    },
    handleData() {
      console.log('222')
      // 复制新增把id,编码,创建人置为空,子表去掉id
      this.basicForm.id = ''
      this.basicForm.planCode = ''
      this.basicForm.createBy = ''
      if (this.basicForm.mkBoPlanItemList.length !== 0) {
        this.basicForm.mkBoPlanItemList.forEach(item => {
          if (item.id) {
            delete item.id
          }
          if (item.planId) {
            delete item.planId
          }
        })
      }
    },
    // 如果需要回显则调用详情接口
    getDetails(row) {
      getPlanDetail(row.id).then(res => {
        if (res.code === 200) {
          // console.log('res', res)
          this.basicForm = res.data
        }
      })
    },
    async save() {
      if(this.basicForm.mkBoPlanItemList.length !== 0) {
        this.$refs['basic'].validate((valid) => {
          if(valid) {
            this.$modal.loading("保存中...");
            if(this.sonPageStu == 'add') {
              this.handleData()
              addPlan(this.basicForm).then(res => {
                console.log(333)
                if (res.code === 200) {
                  this.$modal.msgSuccess("保存成功");
                  this.$modal.closeLoading();
                  this.back()
                }
              }).catch(err => {
                this.$modal.closeLoading();
              })
            } else if (this.sonPageStu == 'edit') {
              let list = []
              list.push(...this.basicForm.mkBoPlanItemList, ...this.delPlanItemList)
              // 深拷贝一下参数对象
              let param = JSON.parse(JSON.stringify(this.basicForm))
              console.log('深拷贝对象',param);
              param.mkBoPlanItemList = list
              // this.basicForm.mkBoPlanItemList.push(...this.delPlanItemList)
              editPlan(param).then(res => {
                if (res.code === 200) {
                  this.$modal.msgSuccess("编辑成功");
                  this.$modal.closeLoading();
                  this.back()
                }
              }).catch(err => {
                this.$modal.closeLoading();
              })
            }
          }
        })
      } else {
        this.$modal.msgWarning("明细信息不能为空！");
      }
    },
    // submit() {
    //   this.$modal.loading("提交中...");
    //   submitDemand(this.basicForm).then(res => {
    //     if (res.code === 200) {
    //       this.$modal.msgSuccess("提交成功");
    //       this.$modal.closeLoading();
    //       this.back()
    //     }
    //   }).catch(err => {
    //     this.$modal.closeLoading();
    //   })
    // },
    // 增行
    addLine(date) {
      if (this.isFlag) {
        date = this.getCurrentTime();
      }
      const newLine = {
        contacts: null,
        id: null,
        planId: null,
        planCode: null,
        date: date,
        customer: null,
        customerName: null,
        contact: null,
        contactName: null,
        address: null,
        purpose: null,
        bo: null,
        boName: null,
        marketingCampaign: null,
        delFlag: 0,
        // 新增字段
        model: null,
        storageCondition: null,
        transportationCondition: null,
      }
      this.basicForm.mkBoPlanItemList.push(newLine)
    },
    // 批量删除按钮
    delItems() {
      if(this.ids.length == 0) {
        this.$modal.msgWarning("请选中至少一条数据");
      } else {
        let param = this.ids.join()
        this.$modal.confirm('确认信息').then(() => {
        delPlanItem(param).then(res => {
          if (res.code === 200) {
            this.$modal.msgSuccess("删除成功");
            this.getDetails(this.row)
          }
        })
        }).catch(() => {})
      }
    },
    delLine(index, row) {
      console.log('删除行:', index)
      console.log('改变行:', row)
      // this.basicForm.mkBoPlanItemList = this.basicForm.mkBoPlanItemList.filter(item => {
      //   return item.id !== row.id
      // })
      row.delFlag = '2'
      // this.basicForm.mkBoPlanItemList.splice(index,1)
      let delList = []
      delList = this.basicForm.mkBoPlanItemList.filter(item => {
        return item.delFlag == '2'
      })
      this.basicForm.mkBoPlanItemList = this.basicForm.mkBoPlanItemList.filter(item => {
        return item.delFlag == '0'
      })
      this.delPlanItemList.push(...delList)
      console.log('删除的数组',this.delPlanItemList)
    },
    edit() {
      this.isFlag = true;
      this.sonPageStu = 'edit'
      this.sonDisable = false
      this.basicForm.mkBoPlanItemList.forEach(item => {
        item.planCode = this.basicForm.planCode
      })
    },
    back() {
      this.$emit('jugislist', true)
      // let queryParams = {
      //   pageNum: 1,
      //   pageSize: 10
      // }
      this.$emit('refresh')
    },
    // 如果需要回显则调用详情接口
    getDetails(row) {
      getPlanDetail(row.id).then(res => {
        if (res.code === 200) {
          this.basicForm = res.data
          for (let i = 0; i < this.basicForm.mkBoPlanItemList.length; i++) {
            this.basicForm.mkBoPlanItemList[i].planCode = res.data.planCode
          }
        }
      })
    },
    // 单元格标红
    cellClassName({row, column, rowIndex, columnIndex}) {
      if(this.basicForm.isSpeical == 'N' && column.label == '需求可用周期' && Number(row.demandPeriod) > 1.5 && Number(row.demandPeriod) > Number(row.minOrderQty)) {
        return 'success-row';
      }
    },
    // handleSelectionChange(selection) {
    //   this.ids = selection.map(item =>{
    //     return item.id
    //   })
    //   console.log('选中数组', this.ids)
    // },
    handleSelectionChange(selection) {
      console.log('选中', selection)
      this.ids = selection.map(item => item.id)
      console.log('选中数组', this.ids.join())
    },
    // 回显参照框
    reBackRefer(type, id, title) {
      getRefer({type: type, id: id}).then(res => {
        if(type == 'MK_SALESAREA_PARAM') {
          this.salesAreaOptions = res.rows
        }
        if (type == 'CUSTOMER_PARAM_ZT') {
          this.customerOptions = res.rows
        }
        if (type == 'CONTACTS_PARAM') {
          this.personOptions = res.rows
        }
        if (type == 'LINKMAN_PARAM') {
          this.linkOptions = res.rows
        }
        if (type == 'DEPT_PARAM') {
          this.deptOptions = res.rows
        }
      })
    },
    // 基本信息选择参照带出数据
    choose(type, isPage, title) {
      this.referCondition.type = type
      this.referCondition.isPage = isPage
      this.referCondition.title = title
      this.$refs.refer.init(this.referCondition)
    },
    // 明细行选择参照带出数据
    chooseSon(index, type, isPage, title, parame) {
      this.tableIndex = index
      this.referCondition.type = type
      this.referCondition.isPage = isPage
      this.referCondition.title = title
      this.referCondition.parame = parame
      this.$refs.refer.init(this.referCondition)
    },
    selectionsToInput(selection) {
      if(this.referCondition.type == 'CUSTOMER_PARAM_ZT') {
        this.customerOptions = selection
        this.basicForm.mkBoPlanItemList[this.tableIndex].customer = selection[0].id
        this.basicForm.mkBoPlanItemList[this.tableIndex].customerName = selection[0].name
      }
      if(this.referCondition.type == 'CONTACTS_PARAM') {
        this.personOptions = selection
        this.basicForm.charger = selection[0].id
        this.basicForm.chargerName = selection[0].name
      }
      if(this.referCondition.type == 'MK_SALESAREA_PARAM') {
        this.salesAreaOptions = selection
        this.basicForm.marketingArea = selection[0].id
        this.basicForm.marketingAreaName = selection[0].name
      }
      if(this.referCondition.type == 'DEPT_PARAM') {
        this.deptOptions = selection
        this.basicForm.dept = selection[0].id
        this.basicForm.deptName = selection[0].name
      }
      if(this.referCondition.type == 'LINKMAN_PARAM') {
        this.linkOptions = selection
        this.basicForm.mkBoPlanItemList[this.tableIndex].contact = selection[0].id
        this.basicForm.mkBoPlanItemList[this.tableIndex].contactName = selection[0].name
      }
    },
    //获取当前时间
    getCurrentTime() {
      let date = new Date();
      return date;
    },
    //获取下周七天日期,day表示想要星期几
    getNextWeek(day) {
      const week = [];
      for (let i = 0; i < 7; i++) {
        let Stamp = new Date();
        let num = 7-Stamp.getDay() + 1 + i;
        Stamp.setDate(Stamp.getDate() + num);
        week[i] = Stamp.getFullYear() + '-' + (Stamp.getMonth() + 1) + '-' + Stamp.getDate();
      }
      return week[day - 1];
    },
    //新增时默认带出num条明细行
    defaultDetailLine(num) {
      for (let i = 0; i < num; i++) {
        this.addLine(this.getNextWeek(i + 1));
      }
      this.isFlag = true;
    }
  }
}

</script>

<style lang="scss" scoped>
.btn_group {
  width: 100%;
  margin: 20px 0;
  display: flex;
  justify-content: center;
} 
.btn_grooup {
  margin-bottom: 10px;
  display: flex;
  justify-content: flex-end;
}
.hang {
  margin: auto;
}
.hang ::v-deep .el-form-item__content{
  margin-left: 0px !important;
}
.el-table ::v-deep .el-form-item__error{
  padding-top: 0;
  top: 70%
}
.el-table ::v-deep .success-row {
  background: #f11616;
}
</style>