<template>
  <div>
    <el-table
      :data="tableData"
      class="plant-table"
      border>
    >
      <el-table-column
        v-for="item in tableColums"
        :key="item.label"
        :label="item.label"
        :width="item.widthsty"
        :min-width="item.minwidthsty"
        align="center"
      >
        <template #header>
          <span>
            {{item.label}}
            <el-tooltip :content="item.tip" placement="top">
              <i class="el-icon-warning" v-if="item.tip"></i>
            </el-tooltip>
          </span>
        </template>
        <template slot-scope="{row}">
          <template v-if="$route.query.type!=='look'">
            <!-- 地点 -->
            <span v-if="item.key==='address'">
              <v-distpicker 
                :province="row.Province"
                :city="row.City"
                :province-source="province_sorce"
                :city-source="city_sorce"
                hide-area 
                @selected="changeArea($event,row)"
              />
            </span>
            <!-- 工厂 -->
            <span v-else-if="item.key==='FactoryName'">
              <el-input
                v-model="row.FactoryName"
                class="large-sty"
                placeholder="请输入工厂"
                @change="saveHandle(row)"
              />
            </span>
            <!-- 装置 -->
            <span v-else-if="item.key==='PlantName'">
              <el-input
                v-model="row.PlantName"
                class="large-sty"
                placeholder="请输入装置/产线"
                @change="saveHandle(row)"
              />
            </span>
            <!-- 年产能 -->
            <span v-else-if="item.key==='AnnualCapacity'">
              <el-input
                v-model="row.AnnualCapacity"
                type="number"
                class="large-sty"
                placeholder="请输入年产能"
                @change="changeParams(row)"
              />
            </span>
            <!-- 检修日期 -->
            <span v-else-if="item.key==='MaintenanceDate'">
              <el-date-picker
                v-model="row.MaintenanceDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="检修日期"
                @change="changeDate(row)"
                style="width: 140px"
              />
            </span>
            <!-- 复产日期 -->
            <span v-else-if="item.key==='ResumptionDate'">
              <el-date-picker
                v-model="row.ResumptionDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="复产日期"
                style="width: 140px"
                @change="() => {row.IsStop=0;changeDate(row)}  "
              />
              <el-checkbox v-model="row.IsStop" @change="changeStopStatus($event,row)" :true-label="1" :false-label="0">退市</el-checkbox>
            </span>
            <!-- 降负系数 -->
            <span v-else-if="item.key==='Coefficient'">
              <el-input
                v-model="row.Coefficient"
                type="number"
                placeholder="请输入降负系数"
                class="large-sty"
                @change="changeParams(row)"
              />
            </span>
            <!-- 日均产量 -->
            <span v-else-if="item.key==='AverageDailyCapacityReductionTon'">
              <el-input
                v-model="row.AverageDailyCapacityReductionTon"
                type="number"
                class="large-sty"
                placeholder="请输入日均产量减量"
                @change="()=> { row.AverageDailyCapacityReduction=row.AverageDailyCapacityReductionTon/10000;saveHandle(row)}"
              />
            </span>
            <span v-else-if="['Day','CapacityReduction'].includes(item.key)">
              {{(row.MaintenanceDate&&row.ResumptionDate&&!row.IsStop)?row[item.key]:'--'}}
            </span>
            <span v-else>{{row[item.key]}}</span>
          </template>
          
          <!-- 查看 -->
          <template v-else>
            <span v-if="item.key==='address'">{{row.Province===row.City?row.City:row.Province+row.City}}</span>
            <span v-else-if="item.key==='ResumptionDate'">{{row.IsStop?'停产':row.ResumptionDate}}</span>
            <span v-else-if="['Day','CapacityReduction'].includes(item.key)">
              {{(row.MaintenanceDate&&row.ResumptionDate&&!row.IsStop)?row[item.key] :'--'}}
            </span>
            <span v-else>{{row[item.key]}}</span>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" v-if="$route.query.type!=='look'" width="200">
        <template slot-scope="scope">
          <el-button type="text" @click="addRow(scope,'copy')">复制</el-button>
          <el-button type="text" @click="addRow(scope,'prev')">向上添加</el-button>
          <el-button type="text" @click="addRow(scope,'next')">向下添加</el-button>
          <span @click="delPlant(scope.row,scope.$index)" class="deletesty">删除</span>
          <el-button type="text" @click="addOtherPlantHandle(scope.row.VarietyPlantId)">添加其他装置</el-button>
        </template>
      </el-table-column>
      <div slot="empty" style="padding: 20px 0">
        <img src="~@/assets/img/cus_m/nodata.png" alt="" style="display:block;width:128px;height:128px;margin: 0 auto;">
        <span>暂无信息</span>
      </div>
    </el-table>

    <!-- 添加其他装置 -->
    <addOtherPlantDia
      :isShow.sync="isAddOtherPlantDialog"
      :plantId="plantId"
      @success="$emit('getData')"
    />
  </div>
</template>

<script>
import{province_sorce,city_sorce} from '@/utils/distpicker';
import * as supplyApi from '@/api/modules/supplyApi.js';
import addOtherPlantDia from './addOtherPlantDia.vue';
import * as $calculate from '@/utils/calculate.js'
export default {
  props: {
    data: Array
  },
  components: {addOtherPlantDia},
  watch: {
    data(nval) {
      this.tableData = nval.length ? nval : this.initTable;
    }
  },
  data() {
    return {
      province_sorce,
      city_sorce,
      tableData: this.data,
      tableColums: [
        {
          label: '地点',
          key: 'address',
          minwidthsty: '120px'
        },
        {
          label: '工厂',
          key: 'FactoryName'
        },
        {
          label: '装置/产线',
          key: 'PlantName'
        },
        {
          label: '年产能(万吨)',
          key: 'AnnualCapacity'
        },
        {
          label: '检修日期',
          key: 'MaintenanceDate',
          widthsty: '150px'
        },
        {
          label: '复产日期',
          key: 'ResumptionDate',
          tip: '默认检修结束日期为复产日期',
          widthsty: '220px'
        },
        {
          label: '降负系数',
          key: 'Coefficient',
          widthsty: '80px',
          tip: '1表示停产,0.1表示降负10%'
        },
        {
          label: '日均产量减量(吨)',
          key: 'AverageDailyCapacityReductionTon',
          widthsty: '100px',
        },
        {
          label: '时长',
          key: 'Day',
          widthsty: '80px',
        },
        {
          label: '期间减量(万吨)',
          key: 'CapacityReduction',
          widthsty: '80px',
        },
      ],

      initTable: [{
          VarietyPlantId: 0,
          Province: '',
          City: '',
          FactoryName: '',
          PlantName: '',
          MaintenanceDate: '',
          ResumptionDate: '',
          AnnualCapacity: 0,
          Coefficient: 1,
          AverageDailyCapacityReduction: 0,
          AverageDailyCapacityReductionTon: 0,
          Day: 0,
          CapacityReduction: 0,
          Button: {
            Edit: true,
            Delete: true
          }
      }],
      
      insertIndex: {
        PrevVarietyPlantId: 0,
        NextVarietyPlantId: 0
      },

      /* 添加其他装置弹窗 */
      isAddOtherPlantDialog: false,
      plantId: 0,
    }
  },
  methods: {
    async delPlant({VarietyPlantId},index) {
      if(VarietyPlantId) {
        await this.$confirm('删除后不可恢复，确认删除吗？','提示',{ type: 'warning' })
        const res = await supplyApi.delPlant({VarietyPlantId});
        if(res.Ret !== 200) return
  
        this.$message.success('删除成功');
        this.$emit('getData')
      }else {
        this.tableData.splice(index,1)
      }
    },

    /* 日期改变 */
    changeDate(row) {
      const { ResumptionDate,MaintenanceDate }  = row;
      if(MaintenanceDate && ResumptionDate && new Date(ResumptionDate).getTime() <= new Date(MaintenanceDate).getTime()) {
        this.$message.warning('复产日期不得早于检修日期 ')
        row.ResumptionDate = '';
        return
      }

      this.saveHandle(row);
    },

    /* 地区改变 */
    changeArea(area,row) {
      row.City = area.city.value;
      row.Province = area.province.value;
      this.saveHandle(row);
    },


    /* 停产 */
    changeStopStatus(val,row) {
      if(val) row.ResumptionDate = '';
      this.saveHandle(row);
    },

    /* 产能改变 */
    changeParams(row) {
      const { Coefficient,AnnualCapacity }  = row;
      row.AverageDailyCapacityReduction = AnnualCapacity/Number(this.$parent.varietyInfo.ProductionDay)*Coefficient;
      row.AverageDailyCapacityReductionTon = $calculate.multiply(row.AverageDailyCapacityReduction,10000);
      this.saveHandle(row);
    },

    /* 添加行 */
    addRow({row,$index},type) {
      const row_item = type === 'copy' ? {
        ...row,
        VarietyPlantId: 0
      } : {
          VarietyPlantId: 0,
          Province: '',
          City: '',
          FactoryName: '',
          PlantName: '',
          MaintenanceDate: '',
          ResumptionDate: '',
          AnnualCapacity: 0,
          Coefficient: 1,
          AverageDailyCapacityReduction: 0,
          AverageDailyCapacityReductionTon: 0,
          Day: 0,
          CapacityReduction: 0,
          Button: {
            Edit: true,
            Delete: true
          } 
      }
      
      this.insertIndex =  {
        PrevVarietyPlantId: type === 'prev' ? 0 : row.VarietyPlantId,
        NextVarietyPlantId: type === 'prev' ? row.VarietyPlantId : 0
      }
      
      type === 'prev' ? this.tableData.splice($index,0,row_item) : this.tableData.splice($index+1,0,row_item)

      this.saveHandle(row_item);
      
    },

    /* 保存 */
    saveHandle: _.debounce(async function(row) {
      const { VarietyPlantId,Province,City,FactoryName,PlantName,MaintenanceDate,ResumptionDate,AnnualCapacity,Coefficient,AverageDailyCapacityReduction,IsStop} = row;

      let params = {
        Province,
        City,
        FactoryName,
        PlantName,
        MaintenanceDate,
        ResumptionDate,
        AnnualCapacity: Number(AnnualCapacity),
        Coefficient: Number(Coefficient),
        AverageDailyCapacityReduction: Number(AverageDailyCapacityReduction),
        IsStop,
      }

      const res = VarietyPlantId
        ? await supplyApi.editPlant({ VarietyPlantId,...params})
        : await supplyApi.addPlant({VarietyId: Number(this.$route.query.id), ...params,...this.insertIndex})

      if(res.Ret !== 200) return
      // this.$message.success('保存成功');
      VarietyPlantId ? this.updatedData(row) : this.$emit('getData')
    },200),

    /* 添加其他装置 */
    addOtherPlantHandle(VarietyPlantId) {
      this.plantId = VarietyPlantId;
      this.isAddOtherPlantDialog = true;
    },

    /* 编辑完更新市场和期间减量 */
    updatedData(row) {
      if(row.MaintenanceDate&&row.ResumptionDate&&!row.IsStop&&row.AverageDailyCapacityReduction) {
        let day = this.$moment(row.ResumptionDate).diff(this.$moment(row.MaintenanceDate), 'day')+1;
        row.Day = day;
        row.CapacityReduction = (row.Day * row.AverageDailyCapacityReduction).toFixed(2);
      }
    }
  }
}
</script>

<style lang="scss">
.plant-table {
  .cell {
    padding: 0 5px;
  }
  .cell .large-sty .el-input__inner {
    padding: 0 4px;
  }
  .cell .distpicker-address-wrapper select {
    width: 120px;
  }
}
</style>