<template>
  <div>
    <el-dialog
      width="1000px"
      :visible.sync="dialogVisible"
      :open="open"
      :title="title"
      v-if="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <el-form
        ref="form"
        v-form
        data-vv-scope="form"
        :model="form"
        :rules="rules"
        label-width="110px"
        disabled
      >
        <el-collapse v-model="activeNames">
          <el-collapse-item name="1">
            <template slot="title">
              <span class="tip"></span>合同信息
            </template>
            <el-card>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="项目名称" prop="projectName">
                    <el-input
                      v-model="form.projectName"
                      placeholder="所属项目"
                      ref="projectName"
                      @focus="handleFocusProject"
                    >
                      <!-- <el-button
                  type="primary"
                  @click="openProject"
                  slot="append"
                  icon="el-icon-search"
                ></el-button> -->
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="合同类型" prop="contractType">
                    <dict-select
                      dictCode="xmht-htlx"
                      :hasDefaultOption="true"
                      clearable
                      v-model="form.contractType"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <!-- <el-col :span="12">
            <el-form-item
              label="所属公司"
              prop="companyName"
            >
              <eip-org-selector
                v-model="form.companyName"
                :permission="permission"
                :single="true"
                append-to-body
                :config="{id:'form.companyId', name: 'form.companyName'}"
                placeholder="请选择"
              />
            </el-form-item>
          </el-col> -->
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="合同编号" prop="contractNumber">
                    <el-input
                      v-model="form.contractNumber"
                      placeholder="合同编号"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="合同名称" prop="contractName">
                    <el-input
                      v-model="form.contractName"
                      placeholder="合同名称"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="分类编号" prop="classificationNumber">
                    <el-input
                      v-model="form.classificationNumber"
                      placeholder="分类编号"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="单位确定方式" prop="confirmationMode">
                    <el-input
                      v-model="form.confirmationMode"
                      placeholder="单位确定方式"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="签约日期" prop="contractDate">
                    <el-date-picker
                      v-model="form.contractDate"
                      type="date"
                      placeholder="选择日期"
                      value-format="yyyy-MM-dd"
                      format="yyyy-MM-dd"
                      style="width: 100%"
                    >
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="立项人" prop="contractInitiator">
                    <eip-user-selector
                      v-model="form.contractInitiator"
                      :config="{name: 'form.contractInitiator'}"
                      :single="true"
                      append-to-body
                      placeholder="请选择"
                      permission="r"
                    />
                    <!-- <el-input
                v-model="form.contractInitiator"
                placeholder="立项人"
              ></el-input> -->
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="甲方" prop="firstParty">
                    <eip-org-selector
                      v-model="form.firstParty"
                      :permission="permission"
                      :single="true"
                      append-to-body
                      :config="{name: 'form.firstParty'}"
                      placeholder="请选择"
                    />
                    <!-- <el-input
                v-model="form.firstParty"
                placeholder="甲方"
              ></el-input> -->
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="乙方" prop="secondParty">
                    <eip-org-selector
                      v-model="form.secondParty"
                      :permission="permission"
                      :single="true"
                      append-to-body
                      :config="{name: 'form.secondParty'}"
                      placeholder="请选择"
                    />
                    <!-- <el-input
                v-model="form.secondParty"
                placeholder="乙方"
              ></el-input> -->
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="丙方" prop="thirdParty">
                    <eip-org-selector
                      v-model="form.thirdParty"
                      :permission="permission"
                      :single="true"
                      append-to-body
                      :config="{name: 'form.thirdParty'}"
                      placeholder="请选择"
                    />
                    <!-- <el-input
                v-model="form.thirdParty"
                placeholder="丙方"
              ></el-input> -->
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="保证金" prop="retentionMoney">
                    <el-input
                      v-model="form.retentionMoney"
                      placeholder="保证金"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="结算金额" prop="settlementAmount">
                    <el-input
                      v-model="form.settlementAmount"
                      placeholder="结算金额"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="唯一编号" prop="uniqueNumber">
                    <el-input
                      v-model="form.uniqueNumber"
                      placeholder="唯一编号"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="合同金额" prop="contractAmount">
                    <el-input
                      v-model="form.contractAmount"
                      placeholder="合同金额"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="合同内容" prop="contractContents">
                    <el-input
                      type="textarea"
                      rows="5"
                      v-model="form.contractContents"
                      placeholder="合同内容"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="备注" prop="remarks">
                    <el-input
                      type="textarea"
                      v-model="form.remarks"
                      placeholder="备注..."
                      rows="5"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-card>
          </el-collapse-item>
        </el-collapse>
      </el-form>
      <el-col :span="24">
        <el-button
          type="primary"
          icon="el-icon-plus"
          style="margin-bottom: 10px; margin-left: 40px"
          @click="addTableData"
          :disabled="isDisabled"
        >
          添加
        </el-button>
      </el-col>
      <el-table
        :data="projectContractPayment"
        border
        :row-key="key"
        style="width: 930px; margin-left: 40px"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          prop="projectCode"
          label="科目名称"
          width="150"
          align="center"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-select
              :disabled="isDisabled"
              v-model="scope.row.projectCode"
              placeholder="请选择"
              @change="val => changesele(val, scope.row.key)"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <!-- <el-input v-model='scope.row.projectCode'></el-input> -->
            <!-- <dict-select
                  dictCode="CBKM"
                  :hasDefaultOption="true"
                  clearable
                  v-model="scope.row.projectCode"
                /> -->
          </template>
        </el-table-column>
        <el-table-column
          prop="subjectCode"
          label="细科目名称"
          width="150"
          align="center"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-select
              :disabled="isDisabled"
              v-model="scope.row.subjectCode"
              placeholder="请选择"
            >
              <el-option
                v-for="item in cbkm"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          prop="payDate"
          label="支付时间"
          align="center"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <!-- <el-input v-model="scope.row.payDate"></el-input> -->
            <el-date-picker
              :disabled="isDisabled"
              v-model="scope.row.payDate"
              type="date"
              width="100%"
              placeholder="支付时间"
              value-format="yyyy-MM-dd"
            >
            </el-date-picker>
          </template>
        </el-table-column>
        <el-table-column
          prop="unit"
          label="单位"
          align="center"
          show-overflow-tooltip
        >
          <template v-slot="{row}">
            <el-input :disabled="isDisabled" v-model="row.unit"></el-input>
          </template>
        </el-table-column>
        <el-table-column
          prop="price"
          label="单价"
          align="center"
          show-overflow-tooltip
        >
          <template v-slot="{row}">
            <el-input
              :disabled="isDisabled"
              type="number"
              v-model="row.price"
              @input="calculation(row)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          prop="amount"
          label="数量"
          align="center"
          show-overflow-tooltip
        >
          <template v-slot="{row}">
            <el-input
              :disabled="isDisabled"
              type="number"
              @input="calculation(row)"
              v-model="row.amount"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          prop="totalPrice"
          label="金额"
          align="center"
          show-overflow-tooltip
        >
          <template v-slot="{row}">
            <el-input
              type="number"
              v-model="row.totalPrice"
              :disabled="isDisabled"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button
              :disabled="isDisabled"
              icon="el-icon-delete"
              type="danger"
              @click="delTableData(scope.row.key, scope.row.id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button @click="handleEnclosure">附件管理</el-button>
        <el-button @click="derive">导 出</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </span>
      <project-info-dialog
        ref="project"
        :single="true"
        @select="handleSelectProject"
      ></project-info-dialog>
    </el-dialog>
    <!-- 附件管理 -->
    <el-dialog
      title="附件管理"
      :visible.sync="dialogVisibleEnclosure"
      width="1000px"
      :before-close="handleCloseEnclosure"
      v-loading="downLoading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-upload
        class="upload-button"
        ref="fileUp"
        :multiple="false"
        :headers="headers"
        :show-file-list="false"
        :action="downLoad"
        :accept="accept"
        :file-list="files"
        :on-success="success"
        :on-error="error"
        :on-progress="progress"
        style="display: inline-block"
      >
        <el-tooltip placement="top" effect="dark">
          <div slot="content">
            附件格式支持:附件大小限制：单个文件不超过50MB
          </div>
          <el-button
            size="small"
            :icon="loading === false ? 'el-icon-upload' : 'el-icon-loading'"
            :disabled="disabled"
          >
            上传文件
          </el-button>
        </el-tooltip>
      </el-upload>

      <el-button
        style="margin-left: 10px"
        type="danger"
        @click="handleEnclosureDel"
        >删除</el-button
      >
      <el-table
        :data="enclosureData"
        border
        ref="multipleTable"
        style="width: 100%; margin-top: 10px"
        @selection-change="handleSelectionChangeEnclosure"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column
          prop="attachmentName"
          label="附件名"
          align="center"
          width="180"
        >
        </el-table-column>
        <el-table-column
          prop="createTime"
          align="center"
          label="创建时间"
          width="180"
        >
        </el-table-column>
        <el-table-column
          prop="attachmentType"
          align="center"
          label="附件类型"
          width="180"
        >
        </el-table-column>
        <el-table-column
          prop="attachmentSuffix"
          label="后缀"
          align="center"
          width="180"
        >
        </el-table-column>
        <el-table-column prop="attachmentPath" align="center" label="附件路径">
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog :visible.sync="exportdialog" title="导出" width="600px">
      <div>
        <span>导出数据：</span>
        <el-button style="width: 100px" @click="exportEX">导出Excle</el-button>
      </div>
      <div style="margin-top: 10px">
        <span>模板下载：</span>
        <el-button style="width: 100px" @click="exportMB">模板下载</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import req from '@/request.js'
import basicData from '@/api/basicData.js'
import ProjectInfoDialog from '@/components/dialog/ProjectInfoDialog.vue'
import eipUserSelector from '@/components/eipControl/selector/EipUserSelector.vue'
import eipOrgSelector from '@/components/eipControl/selector/EipOrgSelector.vue'
import {mapState} from 'vuex'

export default {
  components: {
    eipOrgSelector,
    ProjectInfoDialog,
    eipUserSelector
  },
  computed: mapState({
    // submitUrl: function () {
    //   return `${window.context.portal}/portal/commonBasic/v1/`
    // },
    downLoad: function() {
      return `${window.context.portal}/bizEngineeringAccessories/v1/minioDrawingUpload?sourceId=${this.sourceId}`
    },
    deleteUrl: function() {
      return window.context.yhxt + '/bizProjectContract/v1/updateContract'
    },
    headers: state => {
      return {Authorization: `Bearer ${state.login.currentUser.token}`}
    }
  }),
  data() {
    return {
      isDisabled: true,
      activeNames: '1',
      multipleSelection: {},
      exportdialog: false,
      key: '',
      projectContractPayment: [],
      dialogVisibleEnclosure: false,
      //附件数据
      enclosureData: [],
      //附件管理所需id
      sourceId: '',
      //删除附件管理ids
      ids: [],
      loading: false, //上传附件加载控制
      disabled: false, //按钮禁用控制
      downLoading: false, //文件导出加载控制
      accept:
        '.jpg,.jpeg,.png,.bmp,.pdf,.JPG,.JPEG,.PBG,.BMP,.PDF,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.rtf,.txt,.zip,.rar,.vsd,.dwg,',
      files: [],
      dialogVisible: false,
      title: '',
      row: '',
      form: {
        contractType: 1, //合同类型
        projectName: '',
        projectId: ''
      },
      rules: {
        ascriptionYear: [
          {required: true, message: '里程(千米)', trigger: 'blur'}
        ],
        companyName: [
          {
            required: true,
            message: '请输入公司名称',
            trigger: 'blur'
          }
        ],
        // budgetSum: [
        //   {
        //     required: true,
        //     message: '预算总额',
        //     trigger: 'blur',
        //   },
        // ],
        status: [
          {
            required: true,
            message: '预算单状态',
            trigger: 'blur'
          }
        ],
        startTime: [
          {
            required: true,
            message: '开始时间',
            trigger: 'blur'
          }
        ],
        endTime: [
          {
            required: true,
            message: '结束时间',
            trigger: 'blur'
          }
        ]
        // alreadyCount: [
        //   {
        //     required: true,
        //     message: '已用总额',
        //     trigger: 'blur',
        //   },
        // ],
      },
      permission: 'r',
      options: [],
      cbkm: [],
      selecdVlue: ''
    }
  },
  methods: {
    //附件管理
    handleEnclosure() {
      this.dialogVisibleEnclosure = true
      this.getEnclosureData(this.row.id)
    },
    getEnclosureData(id) {
      const params = {
        pageBean: {
          page: 1,
          pageSize: 20,
          showTotal: true
        },
        params: {},
        querys: [
          {
            group: 'main',
            operation: 'EQUAL',
            parentGroup: '',
            property: 'sourceId',
            relation: 'AND',
            value: id
          }
        ],
        sorter: []
      }
      basicData.getSpecialProjectManagement(2, params).then(res => {
        this.enclosureData = res.rows
      })
    },
    handleCloseEnclosure(done) {
      this.enclosureData = []
      done()
    },
    //文件上传时的钩子
    progress(event, file, fileList) {
      //将图标改成加载图标
      this.loading = true
      //将按钮禁用
      this.disabled = true
    },
    success(response, file, fileList) {
      this.$message.success('文件上传成功')
      //重新加载数据
      this.getEnclosureData(this.sourceId)
      //将图标改成上传图标
      this.loading = false
      //将按钮解禁
      this.disabled = false
    },
    error(response, file, fileList) {
      this.$message.error('文件上传失败')
      delete this.uploadingFiles[Base64.encode(file.name)]
    },
    // //附件导出
    downLoadImg() {
      this.downLoading = true
      const ids = this.unique(this.ids)
      const strs = ids.join(',')
      req
        .download(
          window.context.portal +
            '/bizAccessory/v1/minioDrawingdownFile?ids=' +
            strs
        )
        .then(res => {
          this.downLoading = false
          this.$refs.multipleTable.clearSelection()
          this.ids = []
        })
    },
    //附件管理删除
    handleEnclosureDel() {
      this.downLoading = true
      const ids = this.unique(this.ids)
      // console.log(ids.join(','))
      const strs = ids.join(',')
      basicData.deleteSpecialProjectManagement(strs).then(res => {
        if (res.state) {
          this.$message.success('附件删除成功')
          this.downLoading = false
        } else {
          this.$message.error('附件删除失败')
          this.downLoading = false
        }
        this.getEnclosureData(this.sourceId)
        //清空ids
        this.ids = []
      })
    },
    handleSelectionChangeEnclosure(rows) {
      rows.forEach(item => {
        this.ids.push(item.id)
      })
    },
    //去重
    unique(arr) {
      for (var i = 0; i < arr.length; i++) {
        for (var j = i + 1; j < arr.length; j++) {
          if (arr[i] == arr[j]) {
            //第一个等同于第二个，splice方法删除第二个
            arr.splice(j, 1)
            j--
          }
        }
      }
      return arr
    },
    open(row) {
       this.isDisabled = row.isDisabled
      this.title = '【计量支付】'
      this.dialogVisible = true
      this.$http
        .get('${form}/projectContractPayment/v1/get/' + row.id)
        .then(res => {
          let index = 0
          this.form = res.data.bizProjectContract
          res.data.paymentList.forEach(item => {
            item.key = index++
          })
          this.projectContractPayment = res.data.paymentList
          this.projectContractPayment.forEach(item => {
            this.changesele(item.projectCode, item.key)
          })
        })
      if (this.options.length == 0) {
        let data = 'CBKM'
        basicData.getCostAccountManagement(data).then(res => {
          res.data.forEach(item => {
            console.log(item)
            this.options.push({
              label: item.subjectName,
              value: item.subjectCode
            })
          })
        })
      }
      this.row = row
    },
    formTime(dete) {
      let date = new Date(dete)
      let y = date.getFullYear()
      let m = date.getMonth() + 1
      m = m < 10 ? '0' + m : m
      let d = date.getDate()
      d = d < 10 ? '0' + d : d
      const time = y + '-' + m + '-' + d
      return time
    },
    handleFocusProject() {
      this.$refs.project.open()
    },
    openProject() {
      this.$refs.project.open()
    },
    handleSelectProject(data) {
      console.log(data)
      this.form.projectName = data.projectName
      this.form.projectId = data.projectId
      this.$refs.projectName.focus()
      this.$refs.projectName.blur()
    },
    handleCancel() {
      //清空表单
      this.form = {
        contractType: 1, //合同类型
        projectName: '',
        projectId: ''
      }
      this.options = []
      this.cbkm = []
      this.dialogVisible = false
      this.projectContractPayment = []
    },
    calculation(row) {
      console.log(row, 'row')
      this.projectContractPayment.forEach(item => {
        if (item.price != null && item.amount != null) {
          item.totalPrice = item.price * item.amount
        }
      })
      // let sum = 0
      // this.YStable.forEach((item) => {
      //   if (item.totalPrice) {
      //     sum += item.totalPrice
      //   }
      // })
      // this.form.budgetSum = sum
    },
    addTableData() {
      this.projectContractPayment.push({
        key: this.projectContractPayment.length + 1,
        options: [],
        subjectCode: ''
      })
    },
    changesele(value, key) {
      this.cbkm = []
      let arr = []
      basicData.getCostAccountManagement(value).then(res => {
        if (res.data.length > 0) {
          res.data.forEach(item => {
            if (item.pcode == value) {
              arr.push({
                label: item.subjectName,
                value: item.subjectCode
              })
            }
          })
          this.projectContractPayment.forEach(item => {
            if (item.key == key) {
              this.cbkm = arr
              item.subjectCode = arr[0].value
            }
          })
        } else {
          this.projectContractPayment.forEach(item => {
            if (item.key == key) {
              this.cbkm = []
              item.subjectCode = ''
            }
          })
        }
      })
    },
    handleSubmit() {
      //验证表单是否填写完
      this.dialogVisible = false
      this.$http
        .post(
          '${form}/projectContractPayment/v1/save?contractId=' + this.form.id,
          this.projectContractPayment
        )
        .then(res => {
          console.log(res)
          this.$message.success(res.data.message)
          this.form = {
            contractType: 1, //合同类型
            projectName: '',
            projectId: ''
          }
          this.options = []
          this.cbkm = []
          this.$emit('load')
        })
    },
    derive() {
      this.exportdialog = true
    },
    exportEX() {
      const id = this.unique(this.multipleSelection)
      const strs = id.join(',')
      // let params = new FormData()
      // params.append('ids', strs)
      //   Object.keys(params).forEach((id)=>{
      //       ids.append(id,params[id])
      //   console.log(ids)
      //   })
      // this.$http
      //   .post('${form}/projectContractPayment/v1/exportDatePay?ids='+strs)
      //   .then((res) => {
      //     console.log(res, '321')
      //   })
      let url = '${form}/projectContractPayment/v1/exportDatePay?ids=' + strs
      req.download(url)
    },
    exportMB() {
      // this.$http
      //   .post('${form}/projectContractPayment/v1/downTemplate')
      //   .then((res) => {
      //     console.log(res, '123')
      //   })
      let url = '${form}/projectContractPayment/v1/downTemplate'
      req.download(url)
    },
    //删除表格数据
    delTableData(key, id) {
      //判断是否存在key值
      //删除时调用保存接口
      console.log(key, id)
      this.projectContractPayment = this.projectContractPayment.filter(
        item => item.key !== key
      )
      //调用接口
      this.$http
        .remove(
          '${form}/projectContractPayment/v1/deleteProjectContractPayment?ids=' +
            id
        )
        .then(res => {
          this.$message.success('删除成功')
        })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map(item => {
        return item.id
      })
      //   console.log(this.multipleSelection,'111')
      // this.multipleSelection=val
    }
  }
}
</script>

<style lang="scss" scoped>
/deep/.el-dialog__header {
  border-bottom: 1px solid #eee;
}
.tip {
  display: inline-block;
  width: 6px;
  height: 16px;
  vertical-align: middle;
  margin-right: 6px;
  margin-top: 2px;
  background-color: #211bce;
}
</style>
