<template>
  <ele-modal :visible.sync="visible" :before-close="cancel" :title="`${ addOrEditFlag ? '创建' : '编辑'}委外计划`"
             custom-class="ele-dialog-form" :close-on-click-modal="true" :close-on-press-escape="false" width="80%" :maxable="true">
    <div>
      <el-form :model="formData" ref="form" label-width="120px" class="ele-body" :rules="rules">
        <el-row :gutter="32">

          <el-col :span="4">
            <el-form-item label="计划名称:">
              <el-input size="mini" clearable v-model="formData.name" placeholder="请输入" />
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item label="委外类型:">
              <DictSelection
                dictName="外协委外"
                clearable
                size="mini"
                v-model="formData.outsourceType"
              >
              </DictSelection>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item label="备注:">
              <el-input size="mini" clearable v-model="formData.remark" placeholder="请输入" />
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>


      <ele-pro-table ref="parentTable" :needPage="false" :columns="parentColumns" row-key="idIndex">

        <template v-slot:toolbar>
          <el-button size="small" type="primary" icon="el-icon-plus" class="ele-btn-icon" @click="addOrder">
            添加销售订单
          </el-button>
          <el-button size="small" type="primary" icon="el-icon-plus" class="ele-btn-icon" @click="addPlan">
            添加生产计划
          </el-button>
        </template>

        <template v-slot:action="{ row, $index }">
          <template>
            <el-link
              type="primary"
              :underline="false"
              @click="getOutsource(row)"
            >
              清单
            </el-link>
            <el-popconfirm
              class="ele-action"
              title="确定要删除此销售订单吗？"
              @confirm="remove(row, $index)"
            >
              <template v-slot:reference>
                <el-link type="danger" :underline="false" icon="el-icon-delete">
                  删除
                </el-link>
              </template>
            </el-popconfirm>
          </template>
        </template>


        <template v-slot:expand="{ row, $index }">
          <div style="width:calc(100% - 95px); min-height: 60px; margin-left: 95px;" v-if="row.childrenList && row.childrenList.length > 0">

            <ele-pro-table :toolbar="false" toolsTheme="none" ref="childTable" :need-page="false"
                           :datasource="row.childrenList" :columns="childColumns" :key="row.id + '-'+ $index">

            </ele-pro-table>

          </div>
        </template>

      </ele-pro-table>

    </div>

    <div slot="footer">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="save">保存</el-button>
    </div>

    <orderTablePopup ref="orderTablePopup" @selectOrder="selectOrder"></orderTablePopup>
    <planTablePopup ref="planTablePopup" @selectPlan="selectPlan"></planTablePopup>

  </ele-modal>
</template>

<script>
import orderTablePopup from './orderTablePopup.vue';
import planTablePopup from './planTablePopup.vue';
import dictMixins from '@/mixins/dictMixins';
import { save } from '@/api/outsourcePlan'

export default {
  components: {
    orderTablePopup,
    planTablePopup
  },
  mixins: [
    dictMixins
  ],
  data() {
    return {
      visible: false,
      addOrEditFlag: true,
      formData: {
        name: '',
        outsourceType: null,
        remark: '',
        outsourceList: [],
      },
      rules: {

      },
      parentColumns: [
        {
          width: 45,
          type: 'expand',
          columnKey: 'childrenList',
          align: 'center',
          slot: 'expand'
        },
        {
          prop: 'orderCode',
          label: '销售订单号',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 150,
          slot: 'code',
          sortable: true
        },
        {
          prop: 'planCode',
          label: '计划编号',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 150,
          slot: 'code',
          sortable: true
        },
        {
          prop: 'productCode',
          label: '编码',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 140,
          sortable: true
        },
        {
          prop: 'productName',
          label: '名称',
          align: 'center',
          minWidth: 120
        },
        {
          prop: 'specification',
          label: '规格',
          align: 'center',
          minWidth: 150,

          showOverflowTooltip: true
        },
        {
          prop: 'model',
          label: '型号',
          align: 'center',
          minWidth: 120
        },
        {
          columnKey: 'action',
          label: '操作',
          width: 140,
          align: 'center',
          resizable: false,
          slot: 'action',
          showOverflowTooltip: true
        },
      ],
      childColumns: [

      ],
      tableData: [],
    }
  },
  created() {
  },
  computed: {
    clientEnvironmentId() {
      return this.$store.state.user.info.clientEnvironmentId;
    },
  },
  methods: {
    open(row){
      // 有值为编辑
      if(row){
        this.addOrEditFlag = false;
      }
      this.visible = true;
    },
    selectOrder(row){
      let tableData = this.$refs.parentTable.getData();
      if(row && row.length > 0){
        for (let item of row){
          item.orderId = item.id;
          item.orderCode = item.code;
          tableData.push(item);
        }
      }
      if(this.repeatAdd(tableData)){
        this.$message.warning('重复添加');
      }
      this.createIndex(tableData);
      console.log(tableData);
      this.$refs.parentTable.setData([...tableData])
      this.$forceUpdate()
      this.$nextTick(() => {
        this.$refs.parentTable.toggleRowExpansionAll()
      })
    },
    selectPlan(row){
      let tableData = this.$refs.parentTable.getData();
      if(row && row.length > 0){
        for (let item of row){
          item.planId = item.id;
          item.planCode = item.code;
          item.orderCode = item.salesCode.join(',');
          tableData.push(item);
        }
      }
      if(this.repeatAdd(tableData)){
        this.$message.warning('重复添加');
      }
      this.createIndex(tableData);
      console.log(tableData);
      this.$refs.parentTable.setData([...tableData])
      this.$forceUpdate()
      this.$nextTick(() => {
        this.$refs.parentTable.toggleRowExpansionAll()
      })
    },
    repeatAdd(tableData){
      let flag = false;
      if(tableData && tableData.length){
        for (let i = 0; i < tableData.length -1; i++){
          if(tableData[i].orderCode){
            for (let j = i + 1; j < tableData.length; j++){
              console.log(tableData[i].orderCode)
              console.log(tableData[j].orderCode)
              if(tableData[j].orderCode && tableData[i].orderCode.includes(tableData[j].orderCode)){
                return !flag;
              }
            }
          }
        }
      }
      return flag;
    },
    createIndex(tableData){
      let idIndex = 1;
      if(tableData && tableData.length){
        for (let item of tableData){
          item.idIndex = idIndex++;
        }
      }
    },
    addOrder(){
      console.log('addOrder...........');
      // this.tableData = this.$refs.parentTable.getData();
      this.$refs.orderTablePopup.open();
    },
    addPlan(){
      console.log('addPlan...........');
      // this.tableData = this.$refs.parentTable.getData();
      this.$refs.planTablePopup.open();
    },
    save(){
      this.$refs.form.validate(valid => {
        if(valid){
          let tableData = this.$refs.parentTable.getData() ?? [];
          if (tableData.length == 0) {
            this.$message.info('请至少添加一条销售订单或生产计划！');
            return false;
          }
          console.log('entry....')
          this.formData.outsourceList = tableData;
          console.log(this.formData);
          save(this.formData).then(res => {
            if(res.code == 0){
              this.$message.success('保存成功！');
            } else {
              this.$message.error('保存失败！');
            }
          })
        }
      })

    },
    cancel() {
      console.log('entry...')
      this.visible = false;
      this.$refs.parentTable.setData([]);
      this.$forceUpdate()
    },
    remove(row, index){

    },
    getOutsource(row){
      console.log(row);
    },
  }
}
</script>

<style scoped lang="scss">
:deep(.el-table__expanded-cell) {

  padding-bottom: 30px !important;
  border-bottom: 12px solid #CCFFCC !important;
}
</style>
