<template>
  <el-dialog :title="modalTitle" :visible.sync="modalVisible" :width="formLabelWidth" top="2vh" @close="handleCancel">
    <div class="mobile">
      <div class="hc-box add">
        <div class="hc-box-header">信息</div>
        <div class="hc-box-wrap">
          <el-divider content-position="left">产品基础信息</el-divider>
          <el-form label-width="90px" :model="form" :rules="rules" ref="from" class="from">
            <el-form-item label="产品类型" prop="fkProductType">
              <el-select
                v-model="form.fkProductType"
                @change="getProductAux"
                :disabled="limit.isRead"
                placeholder="请选择产品类型">
                <el-option
                  v-for="(item,index) in productTypelist"
                  :key="index"
                  :label="item.typeName"
                  :value="item.guid"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="产品名称:" prop="productName">
              <el-input
                type="text"
                v-model="form.productName"
                :disabled="limit.isRead"
                placeholder="产品名称"></el-input>
            </el-form-item>
            <el-form-item label="有效时间:" prop="carbonGenerateDate">
               <el-date-picker
                    v-model="form.carbonGenerateDate"
                    type="date"
                    :disabled="limit.isRead"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="选择日期">
               </el-date-picker>
            </el-form-item>
            <el-form-item label="有效周期:" prop="productValidateNum">
              <el-input
                type="number"
                v-model="form.productValidateNum"
                :disabled="limit.isRead"
                placeholder="产品有效周期(年)"></el-input>
            </el-form-item>
            <el-form-item label="碳汇量:" prop="carbonSink">
              <el-input
                type="number"
                v-model="form.carbonSink"
                :disabled="limit.isRead"
                placeholder="产品产生的碳汇量(公斤)"></el-input>
            </el-form-item>
            <el-form-item label="产品备注:">
                <el-input type="textarea"
                          :rows="3"
                          v-model="form.remark"
                          :disabled="limit.isRead"></el-input>
            </el-form-item>
            <el-row :gutter="20">
              <el-col :span="24">
                  <el-divider content-position="left">产品图片</el-divider>
                  <div class="uploadImg">
                      <el-upload
                        v-if="!limit.isRead"
                        accept=".jpg, .png"
                        :headers="upload.headers"
                        :action="upload.url"
                        :disabled="upload.isUploading"
                        :on-progress="handleFileUploadProgress"
                        :on-success="handleFileSuccess"
                        :file-list="fileList">
                        <el-button size="small" type="primary">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                      </el-upload>
                      <ul class="uploadImgList">
                        <li v-for="(item,index) in form.productImgs" :key="index">
                          <img :src="imgRequest + item + '?imageView2/1/w/200/h/200'">
                          <span class="del" @click="handelImgRemove(index)" v-if="!limit.isRead"><i class="el-icon-delete-solid"></i></span>
                        </li>
                      </ul>
                  </div>
              </el-col>
            </el-row>
          </el-form>
          <el-divider content-position="left">产品附属信息</el-divider>
          <div class="productAux">
            <div v-if="productAuxlist.length == 0 " class="productAux-error">
               请注意，该项你可能没选产品类型或该产品类型没有数据，请仔细核对!
            </div>
            <ul v-else>
              <li v-for="(item,index) in productAuxlist">
                  <div class="title">
                    <span class="key">类型属性:</span>
                    <span class="value">{{item.expansionItem}}</span>
                  </div>
                  <div class="value">
                    <el-input v-model="item.expansionVal" placeholder="属性值" :disabled="limit.isRead"></el-input>
                  </div>
              </li>
            </ul>
          </div>
          <el-divider content-position="left">关联帮扶主体</el-divider>
          <div class="relevanceMain">
              <div class="header">
                  <el-radio-group v-model="activeHelpType">
                    <el-radio-button v-for="(item,index) in helpType" :label="item.val">{{item.key}}</el-radio-button>
                  </el-radio-group>
                  <div class="linkSelected">
                    <el-popover
                      placement="top-start"
                      width="900"
                      trigger="hover">
                      <el-table border :data="selecLinksTable">
                          <!--index-->
                          <el-table-column label="序号" type="index" width="50" align="center" fixed/>
                          <!--row name-->
                          <template v-for="(tableTitleItem,index) in activeTabField">
                            <el-table-column
                              :key="index"
                              fixed
                              :align="tableTitleItem.fieldAlign || 'left'"
                              :prop="tableTitleItem.fieldKey"
                              :label="tableTitleItem.fieldName">
                              <template slot-scope="scope">
                                  <span v-if="'povertyArea' === tableTitleItem.fieldKey">{{scope.row.povertyArea.areaAddress}}</span>
                                  <span v-else>{{scope.row[tableTitleItem.fieldKey]}}</span>
                              </template>
                            </el-table-column>
                          </template>
                          <!--action-->
                          <el-table-column
                            label="操作"
                            align="center"
                            width="80"
                            class-name="small-padding fixed-width"
                          >
                            <template slot-scope="scope">
                              <el-button
                                size="mini"
                                v-if="!limit.isRead"
                                type="danger"
                                @click="handleAcdel(scope.row)"
                              >删除</el-button>
                            </template>
                          </el-table-column>
                      </el-table>
                     <el-button type="success" slot="reference" size="small" round>已选({{selecLinksTable.length}})</el-button>
                    </el-popover>
                  </div>
              </div>
              <div class="container">
                  <el-table
                    :data="tableList"
                    ref="linkTable"
                    highlight-current-row
                    v-loading="tableLoading"
                    border
                    max-height="500">
                    <!--index-->
                    <el-table-column label="序号" type="index" width="50" align="center" fixed/>
                    <!--row name-->
                    <template v-for="(tableTitleItem,index) in tabField">
                      <el-table-column
                        :key="index"
                        fixed
                        :align="tableTitleItem.fieldAlign || 'left'"
                        :prop="tableTitleItem.fieldKey"
                        :label="tableTitleItem.fieldName">
                        <template slot-scope="scope">
                            <span v-if="'povertyArea' === tableTitleItem.fieldKey">{{scope.row.povertyArea.areaAddress}}</span>
                            <span v-else>{{scope.row[tableTitleItem.fieldKey]}}</span>
                        </template>
                      </el-table-column>
                    </template>
                    <!--action-->
                    <el-table-column
                      label="操作"
                      align="center"
                      width="120"
                      class-name="small-padding fixed-width"
                    >
                      <template slot-scope="scope">
                        <el-button
                          v-if="!limit.isRead"
                          size="mini"
                          type="primary"
                          @click="handleSelect(scope.row)"
                        >选择</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                  <pagination
                    v-show="total>0"
                    :total="total"
                    :page.sync="queryParams.pageNo"
                    :limit.sync="queryParams.pageSize"
                    @pagination="getHelpInfo"
                  />
              </div>
          </div>
        </div>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="submit" v-if="!limit.isRead">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import tableHeader from "../tableHeader.js"
import { getToken } from "@/utils/auth";
import {
  listProductType ,
  listProductAuxiliary ,
  listCollectiveFarmer ,
  listFarmer ,
  saveProductType,
  detailProduct,
  updateProduct} from "@/api/productManage/productInfo";
export default {
  name: 'addMobiel',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: 'title'
    },
    action: {
      type: String,
      default: 'add'
    },
    selectRow: {
      type: Object,
      default: null
    },
    fkProductTypeId:{
      type:String,
      default:''
    }
  },
  watch: {
    visible(newVal, oldVal) {
      this.modalVisible = newVal;
    },
    title(newVal, oldVal) {
      this.modalTitle = newVal;
    },
    action(newVal, oldVal) {
      this.modalAction = newVal;
    },
    selectRow(newVal, oldVal) {
      this.modalSelectRow = newVal;
    },
    activeHelpType(newVal,oldVal){
      this.queryParams.pageNo = 1
      this.getHelpInfo()
    },
    fkProductTypeId(newVal,oldVal){
      this.modalTypeid = newVal
    }
  },
  data() {
    return {
      modalTitle: this.title,
      modalVisible: this.visible,
      modalAction: this.action,
      modalSelectRow: this.selectRow,
      modalTypeid:this.fkProductTypeId,
      formLabelWidth: '1024px',
      //窗口权限
      limit: {
        isRead: false, //是否只读
        isAdd: false //是否可写
      },
      // 图片上传
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/upload/fileImg",
      },
      //产品类型
      productTypelist:[],
      //产品附属信息
      productAuxlist:[],
      //帮扶主体类型
      helpType:[
        {
           key:"关联单个贫困户",
           val:0
        },
        {
           key:"关联贫困集体",
           val:1
        }
      ],
      activeHelpType:0,
      loading:true,
      tabField:[],
      tableList:[],
      tableLoading:false,
      activeTabField:[],
      selecLinksTable:[],
      //验证
      rules: {
        fkProductType: [{ required: true, message: '产品类型不能为空!', trigger: 'blur' }],
        productName: [{ required: true, message: '产品名称不能为空!', trigger: 'blur' }],
        carbonGenerateDate: [{ required: true, message: '有效期不能为空!', trigger: 'blur' }],
        productValidateNum: [{ required: true, message: '有效周期不能为空!', trigger: 'blur' }],
        carbonSink: [{ required: true, message: '碳汇量不能为空!', trigger: 'blur' }]
      },
      //图片列表
      fileList: [],
      // 关联帮扶分页
      total: 0,
      queryParams: {
        pageNo: 1,
        pageSize: 10
      },
      //表单
      form: {
        productImgs:[],
        productBelongs:[],
        collectiveFarmerForm:[]
      }
    };
  },
  created() {
    this.initPage();
    switch (this.modalAction) {
      case 'add':
        this.limit.isAdd = true;
        //是否选择类型
        if(this.modalTypeid !== ""){
          this.form.fkProductType = this.modalTypeid
          this.getProductAux(this.modalTypeid)
        }
        break;
      case 'edit':
        this.limit.isAdd = true;
        this.getDetail(this.selectRow.guid)
        break;
      case 'view':
        this.limit.isRead = true;
        this.getDetail(this.selectRow.guid)
        break;
      default:
        break;
    }
  },
  mounted() {
    //初始化帮扶主体
    this.getHelpInfo()
  },
  methods: {
    //初始化默认值
    initPage() {
        //获取产品类型
        let typeParams = {
          state: 1
        }
        listProductType(typeParams).then(res => {
            if(res.retHead.errCode == 0){
              this.productTypelist = res.retBody
            }
        });
    },
    //详情查询
    getDetail(id){
      let params = {
        productGuid:id
      }
      detailProduct(params).then(res => {
          if(res.retHead.errCode == 0){
            this.form = res.retBody
            this.form.productImgs = res.retBody.productImgs.split(';')
            this.productAuxlist = res.retBody.productExpansions
            if(res.retBody.productBelongs){
                console.log("productBelongs")
                this.activeHelpType = 0
                this.activeTabField =  tableHeader.singleUser
                this.selecLinksTable = res.retBody.productBelong
                this.form.productBelongs = res.retBody.productBelong
                this.form.collectiveFarmerForm = []
            }else{
                console.log("collectiveFarmerForm")
                this.activeHelpType = 1
                this.activeTabField =  tableHeader.gatherUser
                this.selecLinksTable = res.retBody.collectiveFarmer
                this.form.collectiveFarmerForm = res.retBody.collectiveFarme
                this.form.productBelongs = []
            }
            console.log(this.form)
          }
      });
    },
    //获取产品附属信息
    getProductAux(value){
        let params = {
          guid:value
        }
        listProductAuxiliary(params).then(res => {
            if(res.retHead.errCode == 0){
              this.productAuxlist = res.retBody
            }
        });
    },
    //获取帮扶主体
    getHelpInfo(){
      this.tableList = []
      this.tabField = []
      this.tableLoading = true
      if(this.activeHelpType == 0){
        this.tabField = tableHeader.singleUser
        listFarmer(this.queryParams).then(res => {
            if(res.retHead.errCode == 0){
              this.tableList = res.retBody
              this.total = res.retHead.total
              this.tableLoading = false
            }
        });
      }else{
        this.tabField = tableHeader.gatherUser
        listCollectiveFarmer(this.queryParams).then(res => {
            if(res.retHead.errCode == 0){
              this.tableList = res.retBody
              this.total = res.retHead.total
              this.tableLoading = false
            }
        });
      }
    },
    //帮扶人家选择
    handleSelect(row){
      this.$refs.linkTable.setCurrentRow(row); //选中高亮
      if(this.form.productBelongs.length > 0 || this.form.collectiveFarmerForm.length > 0){
         this.msgError("当前只能选择一个平困户，请先删除后选择!")
         return;
      }else{
         this.selecLinksTable = []  //选中展示
         this.activeTabField = this.activeHelpType == 0 ? tableHeader.singleUser : tableHeader.gatherUser
         this.selecLinksTable.push(row)
         this.form.fkPovertyArea = row.fkPovertyAreaId
         if(this.activeHelpType == 0){
           this.form.productBelongs.push(row)
         }else{
           this.form.collectiveFarmerForm.push(row)
         }
         console.log(this.form)
      }
    },
    //删除已选择帮扶家庭
    handleAcdel(){
      this.activeTabField = []
      this.form.productBelongs = []
      this.form.collectiveFarmerForm = []
      this.selecLinksTable = []
    },
    //表单提交
    submit() {
      this.$refs.from.validate(valid => {
        if (valid) {
          let params = Object.assign({}, this.form);
          params.productImgs = params.productImgs.join(";")
          params.productExpansions = this.productAuxlist
          console.log("未各式前: ",params)
          if(params.collectiveFarmerForm.length == 0) {
            delete params.collectiveFarmerForm
          }
          if(params.productBelongs.length == 0){
            delete params.productBelongs
          }
          console.log("格式化后:",params)
          if(this.selecLinksTable.length == 0){
            this.msgError("请选择关联帮扶主体!")
            return;
          }else{
            if(this.modalAction === 'add'){
              saveProductType(params).then(response => {
                  if (response.retHead.errCode === 0) {
                    this.msgSuccess("操作成功");
                    this.modalVisible = false
                    this.$emit('closecrudmodal', true);
                  }else{
                    this.msgError("保存失败，请检查!");
                  }
              });
            }else{
              updateProduct(params).then(response => {
                  if (response.retHead.errCode === 0) {
                    this.msgSuccess("操作成功");
                    this.modalVisible = false
                    this.$emit('closecrudmodal', true);
                  }else{
                    this.msgError("保存失败，请检查!");
                  }
              });
            }
          }
        } else {
          return false;
        }
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
       this.upload.isUploading = true;
    },
    // 上传成功处理
    handleFileSuccess(response, file, fileList){
       this.fileList = []
       this.form.productImgs.push(response.retBody)
       this.upload.isUploading = false;
    },
    // 图片删除
    handelImgRemove(i){
      this.form.productImgs.splice(i,1)
    },
    //窗口关闭
    handleCancel() {
      this.$emit('closecrudmodal', false);
    }
  }
};
</script>

<style lang="scss" scoped>
.hc-box {
  border: 1px solid #e9e9e9;
  margin-bottom: 20px;
  .hc-box-header {
    height: 40px;
    line-height: 40px;
    background: #fafafa;
    font-weight: bold;
    color: #333;
    padding: 0 15px;
    margin-bottom:20px;
    .action {
      margin-left: 10px;
      color: #304ffe;
    }
  }
  .hc-box-wrap{
    padding-bottom:30px;
    .uploadImg{
      padding:0 30px 30px 30px;
      .uploadImgList{
        list-style:none;
        margin:0;
        padding:15px 0;
        display:flex;
        flex-flow: row;
        li{
          position:relative;
          border:1px solid #ddd;
          border-radius:6px;
          width:120px;
          height:120px;
          margin-right:13px;
          img{
            width:100%;
            height:100%;
            border-radius:6px;
          }
          .del{
            display:none;
            position:absolute;
            top: -9px;
            right: -9px;
            cursor:pointer;
            i{
              font-size:20px;
              color:red;
            }
          }
          &:hover{
            .del{
              display:block;
            }
          }
        }
      }
    }
    .productAux{
      &-error{
        text-align:center;
        padding:20px 0px
      }
      ul,li{
        list-style: none;
        margin:0;
        padding:0;
      }
      li{
        overflow:hidden;
        margin-bottom:15px;
        div{
          float:left;
          height:36px;
        }
        .title{
          width:180px;
          border:1px solid #E6E6E6;
          margin:0 15px 0 20px;
          span{
            display:inline-block;
            height:100%;
            line-height:36px;
            font-size:12px;
            text-align:center;
          }
          .key{
            width:40%;
            border-right:1px solid #E6E6E6;
            background:#FBFBFB;
          }
          .value{
            width:60%;
          }
        }
      }
    }
    .relevanceMain{
      .header{
        padding:0 20px;
        margin-bottom:20px;
        .linkSelected{
          float:right;
        }
      }
      .container{
        padding:0 20px;
      }
    }
  }
}
</style>
